3

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. 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;
}
Arefe
  • 1,029
  • 5
  • 16
  • 30
  • I'm not sure how exactly this algorithm works, but just my personal opinion: use `toCharArray()`, sort it alphabetically, then compare the arrays. – Arc676 Jan 03 '16 at 08:03
  • I know few other ways to do it, I just want to know why this little code is not working. This algorithm keeps track of character using their ASCII values. – Arefe Jan 03 '16 at 08:05
  • Related: http://stackoverflow.com/q/15045640/1079354 – Makoto Jan 03 '16 at 08:30

2 Answers2

3

letters is a char array, so letters[i] can never be negative (the range of char is 0 to 2^16-1). If you try to decrement it below 0, it will underflow to Character.MAX_VALUE. Change it to an int[].

Eran
  • 387,369
  • 54
  • 702
  • 768
1

In the first for loop you are using:

letters[c]++;

when c is a char.
In the other for loop you cast c to int by performing (int)two.charAt(j) before assigning it to 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. You need to change the array to int[128].

Idos
  • 15,053
  • 14
  • 60
  • 75