An easier way might be to just sort the chars in both strings, and compare whether they are equal:
public static boolean isAnagram(String s1, String s2){
// Early termination check, if strings are of unequal lengths,
// then they cannot be anagrams
if ( s1.length() != s2.length() ) {
return false;
}
s1=s1.toLowerCase();
s2=s2.toLowerCase();
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
String sc1 = new String(c1);
String sc2 = new String(c2);
return sc1.equals(sc2);
}
Personally I think it's more readable than nested for-loops =p
This has O(n log n) run-time complexity, where n
is the length of the longer string.
Edit: this is not the optimal solution. See @aam1r's answer for the most efficient approach (i.e. what you should actually say in an interview)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…