我尝试为字谜编写一个小代码,然后我写下了onw.
String s = "anagram";
String t = "nagara";
Map map1 = new HashMap();
Map map2 = new HashMap();
if (s.length() != t.length()) {
System.out.println("Not an anagram");
} else {
for (int i= 0;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 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");
}
}
}
这适用于几乎所有情况,但是当我输入leetcode进行检查时,它会失败,其中一个最长的字谜有50000个字符.
有人能够指出我在这里看错了什么?