判断两个字符串是否是anagram

问题:

所谓 anagram, 就是两个词所用的字母及其个数都是一样的,但是,字母的位置不一样。比如 abcc 和 cbca 就是 anagram. 

分析:

判断的方法比较简单,先把单个字母(字符)转成整数,然后利用了hashtable+计数器的原理进行判断。

 

 1 public static boolean anagrams(String a, String b) {
 2         if (a.length() != b.length()) return false;
 3         int letters[] = new int[256];
 8         //process the string a
 9         for (char c : a.toCharArray()) {
10             ++letters[c]; 
11         }
12         //if the char appears in string b, decrease the corresponding number of counts.
13         for (char c : b.toCharArray()) {
14             if (letters[c] == 0) {
15                 return false;
16             }
17             --letters[c];
18         }
19         
20         //if string a and b are anagrams, all the values in array letters should be 0
21         for (int i = 0; i < letters.length; i++) {
22             if (letters[i] != 0) {
23                 return false;
24             }
25         }    
26         return true;    
27     }

 

转载请注明出处。

 

posted @ 2015-01-06 09:23  北叶青藤  阅读(905)  评论(0)    收藏  举报