所谓 anagram, 就是两个词所用的字母及其个数都是一样的,但是,字母的位置不一样。比如 abcc 和 cbca 就是 anagram.判断的方法比较简单,先把单个字母(字符)转成整数,然后利用了hashtable+计数器的原理进行判断。
public static boolean anagrams(String a, String b) {
if (a.length() != b.length()) return false;
int letters[] = new int[256];
//initialization
for (int i = 0; i < letters.length; i++) {
letters[i] = 0;
}
//process the string a
for (char c : a.toCharArray()) {
++letters[c];
}
//if the char appears in string b, decrease the corresponding number of counts.
for (char c : b.toCharArray()) {
if (letters[c] == 0) {
return false;
}
--letters[c];
}
//if string a and b are anagrams, all the values in array letters should be 0
for (int i = 0; i < letters.length; i++) {
if (letters[i] != 0) {
return false;
}
}
return true;
}
ASCII 表: http://www.asciitable.com/