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?