Last active
August 29, 2018 16:15
-
-
Save xnorcode/aeab060a8f4ce0feb575be77f3be7185 to your computer and use it in GitHub Desktop.
Anagrams Check with Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
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