Can someone explain to me how the marked lines below work? What do they do exactly?
public class GrammerUtils {
public static void main(String args[]) {
System.out.print(isAnagram("teacher", "cheater"));
}
public static boolean isAnagram(String word, String anagram) {
if (word.length() != anagram.length()) {
return false;
}
char[] chars = word.toCharArray(); // marked
for (char c: chars) { // marked
int index = anagram.indexOf(c);// marked
if (index != -1) { // marked
anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
} else {
return false;
}
}
return anagram.isEmpty();
}
}
The code takes one character in the word after another
char[] chars = word.toCharArray();
for (char c: chars) {
and checks if it is in the potential anagram.
int index = anagram.indexOf(c);
If yes
if (index != -1) {
then removes it so that it is not checked again in case there are repetitions (you take the substring before the character and the substring after the character, keep in mind that substring is exclusive in the second parameter):
anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
and goes to the next character (When you finish checking all characters in the word, you check if all the characters in the anagram were matched, i.e. if the anagram is now empty).
If the character is not in the anagram then it means it is not an anagram, and you return false.
return false;
This is rather inefficient (O(n^2)). Better to sort both strings and compare the results (O(n*log(n))