[英]Check whether two String's are anagram
I wrote a method for checking whether two Strings are anagram or not. 我写了一个方法来检查两个字符串是否是字谜。 The method is returning true even if the words are not anagram.
即使单词不是anagram,该方法也会返回true。 I don't see any bug in the code, any ideas how can I improve ?
我没有在代码中看到任何错误,任何想法我怎样才能改进? The method is as following,
方法如下,
public static boolean checkAnagram( String one, String two){
if ( one.length() != two.length() )
return false;
char[] letters = new char[128];
for ( char c: one.toCharArray()){
letters[c]++;
}
for( int j =0; j < two.length(); j++){
int c = (int) two.charAt(j);
if( --letters[c] < 0) return false;
}
return true;
}
letters
is a char
array, so letters[i]
can never be negative (the range of char
is 0
to 2^16-1
). letters
是一个char
数组,所以letters[i]
永远不会是负数( char
的范围是0
到2^16-1
)。 If you try to decrement it below 0, it will underflow to Character.MAX_VALUE
. 如果您尝试将其减少到0以下,它将下溢到
Character.MAX_VALUE
。 Change it to an int[]
. 将其更改为
int[]
。
In the first for
loop you are using: 在第一个
for
循环中,您正在使用:
letters[c]++;
when c
is a char
. 当
c
是一个char
。
In the other for
loop you cast
c
to int
by performing (int)two.charAt(j)
before assigning it to c
. 在其他
for
循环,你会cast
c
以int
通过执行(int)two.charAt(j)
将其分配给前c
。
Also, you are getting true
each time because you can't have a negative value in a char
array, so at every index exists that letters[index] >= 0
. 此外,每次都会变为
true
因为在char
数组中不能有负值,因此在每个索引处都存在letters[index] >= 0
。 You need to change the array to int[128]
. 您需要将数组更改为
int[128]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.