Java – valid anagrams code – one of 32 cases failed Through 31 cases
I tried to write a little code for the puzzle, and then I wrote 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 applies to almost all situations, but when I type leetcode to check, it fails. One of the longest puzzles has 50000 characters Can someone point out what I read wrong here?
Solution
You are a victim of integer caching with a value between - 128 and 127
When you calculate the number of characters in two words and put values into the map as boxed integer objects, 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 combine two integer objects with= Compare instead of using
else if (!entry.getValue().equals(map2.get(entry.getKey())))
This applies to short words because the number of occurrences per character does not exceed the magic value of 127
These values are cached in the integer class, so boxed integers less than (and equal to) the value are the same, and boxed integers greater than the value are different objects with equal values