Try something like this:
public boolean anagram (String s1, String s2) {
int count = 0;
boolean a = false;
for (int i = 0; i < s2.length(); i++) {
int s1index = s1.indexOf(s2.charAt(i));
if (s1index != -1) {
count++;
s1 = s1.replaceFirst(String.valueOf(s1.charAt(s1index)),"");
}
}
if ((count == s2.length()) && (s1.length() == 0))
a = true;
return a;
}
Basically the test should be done at the end of the function and outside the for
loop, and you'd want to return the boolean value of a
, not the boolean value of a == true
(which should be always false
, since a
is never assigned the true
value in your code).
EDIT: I've corrected two mistakes in my initial answer, as well as added code that will hopefully eliminate the issue of multiple occurences of a letter (which is why my first answer didn't work in some cases). This code modifies the s1
string - if you don't want that, just do s1temp = s1;
at the beginning of the function and replace s1
with s1temp
for the rest of the function. The code also uses string's replaceFirst()
method - since the replace
method deletes all occurences of a letter as far as I know, but you can switch to other alternatives that delete a character from a string (see this question for further details). By the way, your temp
approach was incorrectly trying to replace the index of a character, not the actual character, not to mention the fact that a i !=-1
test makes no sense in a for
loop that is incrementing i
starting from 0.
NOTE: You can verify if it's working (with every step printed out on the screen) here (online Java compiler).