Given two strings, determine if one is a permutation of the other (i.e., the two strings are anagrams of each other)
static boolean areAnagrams(String s1, String s2) {
if (null == s1 && null == s2) {
return true;
}
else if (null == s1 ^ null == s2) {
return false;
}
// Both strings are non-null and identical length
else if (s1.length() == s2.length()) {
// char are two-byte primitives in Java
int numChars = Math.pow(2, 16);
int[] s1CharCount = new int[numChars];
int[] s2CharCount = new int[numChars];
countChars(s1, s1CharCount);
countChars(s2, s2CharCount);
for (int i = 0; i < numChars; i++) {
if (s1CharCount[i] != s2CharCount[i]) {
return false;
}
}
return true;
}
return false;
}
static void countChars(String s, int[] charCount) {
for (int i = 0; i < s.length(); i++) {
charCount[Character.numericValue(s.charAt(i))]++;
}
}
No comments:
Post a Comment