所谓 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/
本文介绍了一种使用哈希表和计数器原理来判断两个字符串是否为anagram的有效方法。anagram是指由相同字母组成但排列不同的单词或短语。通过对比两个字符串中每个字符出现的次数来确定它们是否互为anagram。
854

被折叠的 条评论
为什么被折叠?



