Given two strings, write a method to check if one is a permutation of the other. No need to check for case.
Algorithm:
static boolean isPermutation(String str1, String str2) {
if (str1.length() != str2.length()) return false;
if (str1.length() == 0 && str2.length() == 0) return true;
HashMap<Character, Integer> map = new HashMap<>();
// increment all chars from string 1
for (int i = 0; i < str1.length(); i++) {
char c = str1.charAt(i);
if (map.containsKey(c)) {
int val = map.get(c);
map.put(c, ++val);
} else {
map.put(c, 1);
}
}
// decrement all chars from string 2
for (int i = 0; i < str2.length(); i++) {
char c = str2.charAt(i);
if (!map.containsKey(c)) return false;
int val = map.get(c);
map.put(c, --val);
}
// check if all values are zeroed out
for (int val : map.values()) {
if (val != 0) return false;
}
return true;
}