Reputation: 162
I tried writing a small code for anagrams and I wrote the below onw.
String s = "anagram";
String t = "nagara";
Map<Character,Integer> map1 = new HashMap<Character,Integer>();
Map<Character,Integer> map2 = new HashMap<Character,Integer>();
if (s.length() != t.length()) {
System.out.println("Not an anagram");
} else {
for (int i= 0;i<s.length();i++) {
char c = s.charAt(i);
char d = t.charAt(i);
if (map1.containsKey(c)) {
map1.put(c, map1.get(c)+1);
} else {
map1.put(c,1);
}
if (map2.containsKey(d)) {
map2.put(d, map2.get(d)+1);
} else {
map2.put(d,1);
}
}
for (Map.Entry<Character, Integer> entry : map1.entrySet()) {
if (!map2.containsKey(entry.getKey())) {
System.out.println("Not an anagram");
} else if (entry.getValue() != map2.get(entry.getKey())) {
System.out.println("Not an anagram");
}
}
}
This works for almost all casesto check, it fails for one of the longest anagrams with 50000 characters . Would anyone be able to point me on what looks wrong here?
Upvotes: 3
Views: 162
Reputation: 20608
You are a victim of the Integer
caching for values between -128 and +127.
As you are counting the numbers of characters in both words, putting the value as a boxed Integer
object into the map, you need to compare them as objects, not as values.
The problem is this line:
else if (entry.getValue() != map2.get(entry.getKey()))
Here you compare two Integer
objects with !=
instead of using
else if (!entry.getValue().equals(map2.get(entry.getKey())))
The reason why this works for short words is that the occurrence number of each character does not exceed the magical value of 127.
These values are cached in the Integer
class, so that boxed integers less than (and equal to) that value are the same whereas boxed integers greater than that value are different objects with equal value.
Upvotes: 7