首页 > 解决方案 > Java anagram 工作代码,帮助理解代码的概念

问题描述

public static boolean anagramTest(String one, String two){  // two parameter and boolean (true or false)                                        

    String a = one.toLowerCase();   // making value into lower case                                     
    String b = two.toLowerCase();                                       

    if (a.length() != b.length()){     // if value in a is not equal to b, return false                                     
      return false;                                     
    }                                       

    int[] check = new int[50];    // new array called counter with 50 space                                     
    int difference = 0;     // new int labled checker                                       

    for (int i=0;i<a.length(); i++){     // for loop for first length                                       
        int o = (int) a.charAt(i) - 97;  //making char into array index, a numeric value for a?                                       
        if (check[o] >= 0){    // ---                                     
            difference++;                                     
        } else {                                        
            difference--;           // ---                                        
        }                                       
        check[o]++;  // ----                                        

        int t = (int) b.charAt(i) - 97;      //making char into array index                                     
        if (check[t] <= 0){                                     
          difference++;                                     
        } else {                                        
          difference--;                                     
        }                                       
        check[t]--;                                     
    }
} 

我在在线资源的帮助下创建了一个代码main,但我隐约了解它的功能并想确保我完全理解这个概念,所以首先我将两个参数放入新字符串中以转换为小写,如果a不是一样b,它是false。所以我创建了一个新数组和int。一个带有新 int 的 for 循环,其中有一个值,charAt但为什么97,显然你从ato 中减去z?然后它检查差异的增加和减少,对bvalue 进行相同的处理,最后返回 value 0

标签: java

解决方案


我认为分阶段理解更清楚:

1)check数组跟踪在 string 中看到的字母a的频率减去在 string 中看到的字母的频率b。换句话说,在函数的末尾,check[c-'a']表示字符'c'在字符串a中出现的次数减去它在字符串中出现的次数b。(顺便说一下,字符的 ASCII 码a是 97)。

2) 现在从这里开始,您要确保check数组全为零——即:两个字符串中字符的频率是平衡的。如果是这样,这两个字符串是字谜。如果不是,则difference计算的值将是校验数组的绝对值之和。


推荐阅读