[英]Java Anagram - is it the simplest solution other than sorting
I am creating the algorithm to check if two given words are Anagram or not. 我正在创建一种算法来检查两个给定的单词是否为Anagram。 I came up with this simple solution.
我想出了这个简单的解决方案。 But I think it's too simple and I can not find this much simpler solution.
但是我认为这太简单了,我找不到这种更简单的解决方案。 Am I right with this solution?
我对这个解决方案正确吗? or something wrong with this solution?
还是这个解决方案有问题?
public boolean checkAnagram(String a, String b){
if(a.length() != b.length()) return false;
a=a.toLowerCase();
b=b.toLowerCase();
int length= a.length();
int sum1=0;
int sum2=0;
for(int i=0;i<length;i++){
sum1 += a.charAt(i);
sum2 +=b.charAt(i);
}
if(sum1==sum2){
return true;
} else {
return false;
}
}
This solution is wrong - summing values loses a lot of data, specifically, how the values are distributed. 该解决方案是错误的-对值求和会丢失大量数据,尤其是值的分布方式。 Eg, if you feed "AC" and "BB" to this function, you'll get
true
, which is the wrong result. 例如,如果将“ AC”和“ BB”输入此函数,则会得到
true
,这是错误的结果。
Instead, you should count the number of times each character appears in each string and compare them: 相反,您应该计算每个字符出现在每个字符串中的次数并进行比较:
public static boolean checkAnagram(String a, String b){
// optimiztion, will also work without it
if (a.length() != b.length()) {
return false;
}
Map<Character, Long> aMap = countChars(a);
Map<Character, Long> bMap = countChars(b);
return a.equals(b);
}
private static Map<Character, Long> countChars(String s) {
return s.chars()
.mapToObj(c -> Character.toLowerCase((char) c))
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
}
This won't work as ac
is equal to bb
. 这将不起作用,因为
ac
等于bb
。
You need to actually keep track of the characters: 您实际上需要跟踪字符:
int[] aArr = new int[26];
int[] bArr = new int[26];
for(char c : a. toLowerCase().toCharArray()) {
aArr[c - 'a']++;
}
// same for b
return Arrays.equals(aArr, bArr);
Time complexity is O(n)
(with the length check) 时间复杂度为
O(n)
(使用长度检查)
convert the strings to char arrays and use the Arrays.sort() to sort them 将字符串转换为char数组,并使用Arrays.sort()对其进行排序
String str1 = "anagram";
String str1 = "margana";
char arrChar1[]= str1.toLowerCase().toCharArray();
char arrChar2[]= str2.toLowerCase().toCharArray();
Arrays.sort(arrChar1);
Arrays.sort(arrChar2);
System.out.println(Arrays.equals(arrChar1,arrChar2));//check if is equals with char to char
//if true is anagram if false is not
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.