java - 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
,显然你从a
to 中减去z
?然后它检查差异的增加和减少,对b
value 进行相同的处理,最后返回 value 0
。
解决方案
我认为分阶段理解更清楚:
1)check
数组跟踪在 string 中看到的字母a
的频率减去在 string 中看到的字母的频率b
。换句话说,在函数的末尾,check[c-'a']
表示字符'c'
在字符串a
中出现的次数减去它在字符串中出现的次数b
。(顺便说一下,字符的 ASCII 码a
是 97)。
2) 现在从这里开始,您要确保check
数组全为零——即:两个字符串中字符的频率是平衡的。如果是这样,这两个字符串是字谜。如果不是,则difference
计算的值将是校验数组的绝对值之和。
推荐阅读
- c - 使用 fgetc() 将文件中的整数值分配给数组
- javascript - 我的代码可以在代码笔中使用,但不能在本地使用
- android - 有没有办法通过 EAP-TTLS 以编程方式连接到 Passpoint/Hotspot2.0 网络?
- python - 使用python扫描文件夹内所有确定的文件
- pip - 如何在 Windows 上为 python 3.3 安装 pip?
- amazon-web-services - 无服务器 - 无法从 S3 读取文件
- java - 如何在 Android 上管理从后台恢复的 Xamarin 表单应用程序?
- hadoop - 在 Web UI 中何处使用 HDFS 数据 - MapR
- python - 查找总和在目标特定范围内的所有可能组合
- ruby-on-rails - Rails 设计调用 POST 而不是 PUT 重置密码