简体   繁体   English

检查两个String是否为anagram

[英]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的范围是02^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 cint通过执行(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM