Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Last active August 29, 2018 16:15
Show Gist options
  • Save xnorcode/aeab060a8f4ce0feb575be77f3be7185 to your computer and use it in GitHub Desktop.
Save xnorcode/aeab060a8f4ce0feb575be77f3be7185 to your computer and use it in GitHub Desktop.
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