gogogo
管理员
管理员
  • UID25
  • 粉丝0
  • 关注0
  • 发帖数1377
阅读:696回复:0

判断两个字符串是否是anagram;判断两个字符串是否是变位词。

楼主#
更多 发布于:2023-08-22 17:02
所谓 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 = 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 != 0) {
                                return false;
                        }
                }        
                return true;        
        }

转自:
https://blog.csdn.net/beiyeqingteng/article/details/6746494
游客


返回顶部