有效的anagrams代码 - 32个案例中的一个案例失败.通过31例

use*_*864 3 java string anagram

我尝试为字谜编写一个小代码,然后我写下了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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这适用于几乎所有情况,但是当我输入leetcode进行检查时,它会失败,其中一个最长的字谜有50000个字符.有人能够指出我在这里看错了什么?

See*_*ose 7

您是-128和+127之间值的Integer缓存的受害者.

当您计算两个单词中的字符数时,将值作为盒装 Integer对象放入地图中,您需要将它们作为对象进行比较,而不是作为进行比较.

问题是这一行:

else if (entry.getValue() != map2.get(entry.getKey()))
Run Code Online (Sandbox Code Playgroud)

在这里你比较两个Integer对象!=而不是使用

else if (!entry.getValue().equals(map2.get(entry.getKey())))
Run Code Online (Sandbox Code Playgroud)

这适用于短词的原因是每个字符的出现次数不超过127的神奇值.

这些值缓存在Integer类中,因此小于(和等于)该值的盒装整数是相同的,而大于该值的盒装整数是具有相等值的不同对象.