字母异序词

题目:

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false. 

下面是我的实现算法:

public class Solution {
    public boolean isAnagram(String s, String t) {
        char[] array1 = s.toCharArray();
        char[] array2 = t.toCharArray();
        for(int i=0;ichar temp = array1[i];
            for(int j=0;jif(temp == array2[j]){
                    array1[i] = '0';
                    array2[j] = '0';
                    break;
                }
            }
        }
        for(char c:array1){
            if(c!='0'){
                return false;
            }
        }
        for(char c:array2){
            if(c!='0'){
                return false;
            }
        }

        return true;
    }
}

此算法运行效率太低,下面这个算法更好:

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        int bit[] = new int[26];
        for(int i=0;i'a']++;
        }

        for(int i=0;iif(--bit[t.charAt(i)-'a']<0)
                return false;
        }
        return true;
    }

}

你可能感兴趣的:(总结)