Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Last active Aug 29, 2018
Embed
What would you like to do?
Anagrams Check with Array
...
static boolean isAnagram(String str1, String str2){
// not the same size its not anagram
if(str1.length() != str2.length()) return false;
// integer array of 26 for each letter of English alphabet
int[] letters = new int[26];
// check characters of first String against decimal ASCII value of letter "a"
for(char c : str1.toCharArray()){
letters[c - 'a']++;
}
// check characters of second String against decimal ASCII value of letter "a"
for(char c : str2.toCharArray()){
letters[c - 'a']--;
}
// check letters array values if any letter exists in only one of the two Strings
for(int i : letters){
if(Math.abs(i) > 0) return false;
}
// is anagram
return true;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment