加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 有效的anagrams代码 – 32个案例中的一个案例失败.通过3

发布时间:2020-12-15 04:29:54 所属栏目:Java 来源:网络整理
导读:我尝试为字谜编写一个小代码,然后我写下了onw. String s = "anagram";String t = "nagara";MapCharacter,Integer map1 = new HashMapCharacter,Integer();MapCharacter,Integer map2 = new HashMapCharacter,Integer();if (s.length() != t.length()) { Syst
我尝试为字谜编写一个小代码,然后我写下了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");
        }
    }
}

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

解决方法

您是 Integer caching的受害者,其值介于-128和127之间.

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

问题是这一行:

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

在这里,您将两个Integer对象与!=进行比较而不是使用

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读