I was solving this LeetCode problem and can't figure out why one of my solutions doesn't work for the last test case.
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
HashMap<Character, Integer> sHashMap = new HashMap<>();
HashMap<Character, Integer> tHashMap = new HashMap<>();
for (char c : s.toCharArray()) {
sHashMap.put(c, sHashMap.getOrDefault(c, 0) + 1);
}
for (char c : t.toCharArray()) {
tHashMap.put(c, tHashMap.getOrDefault(c, 0) + 1);
}
if (!sHashMap.keySet().equals(tHashMap.keySet())) {
return false;
}
for (char c : sHashMap.keySet()) {
if (sHashMap.get(c) != tHashMap.get(c)) {
return false;
}
}
return true;
}
The last test case has two very long strings and my function returns false
instead of true
.
EDIT: It was because I was comparing Integer
objects using !=
.