有效的字谜代码 - 32 个案例中有 1 个案例失败。 31例通过

问题描述 投票:0回答:1

我尝试编写一个用于字谜的小代码,并编写了以下内容。

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");
        }
    }
}

这适用于几乎所有要检查的情况,对于最长的 50000 个字符的字谜之一,它会失败。 有人能指出我这里看起来有什么问题吗?

java string anagram
1个回答
7
投票

对于 -128 到 +127 之间的值,您是

Integer
缓存 的受害者。

当您计算两个单词中的字符数时,将值作为 boxed

Integer
对象放入地图中,您需要将它们作为 objects 进行比较,而不是作为 values

问题出在这一行:

else if (entry.getValue() != map2.get(entry.getKey()))

在这里,您将两个

Integer
对象与
!=
进行比较,而不是使用

else if (!entry.getValue().equals(map2.get(entry.getKey())))

这对于短单词有效的原因是每个字符的出现次数不超过神奇值127。

这些值缓存在

Integer
类中,因此小于(且等于)该值的装箱整数是 same,而大于该值的装箱整数是具有 equal 值的不同对象。

© www.soinside.com 2019 - 2024. All rights reserved.