Skip to content

Latest commit

 

History

History
52 lines (43 loc) · 959 Bytes

242. Valid Anagram.md

File metadata and controls

52 lines (43 loc) · 959 Bytes

242. Valid Anagram

Problem

tag:

  • sort
  • hashtable

Solution

验证相同字母异序词

Solution1

排序,比较 O(nlogn)

Solution2

哈希表 O(n)

java

    //sort
    // public boolean isAnagram(String s, String t) {
    //     if(s==null||t==null||s.length()!=t.length()) return false;
    //     char[] ss = s.toCharArray();
    //     char[] tt = t.toCharArray();
    //     Arrays.sort(ss);
    //     Arrays.sort(tt);
    //     if(new String(ss).equals(new String(tt))) return true;
    //     return false;
    // }
    
    //map
    public boolean isAnagram(String s, String t) {
        int[] map = new int[26];
        for(int i=0; i<s.length(); i++) {
            map[s.charAt(i)-'a']++;
        }
        for(int i=0; i<t.length(); i++) {
            map[t.charAt(i)-'a']--;
        }
        for(int m : map){
            if(m!=0) return false;
        }
        return true;
    }

go