gpt4 book ai didi

java - 比较 hashMap 值

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:50:42 25 4
gpt4 key购买 nike

我正在练习一些面试题,但不知道如何比较 hashMap 值。前提是你有一本带弦的杂志。您必须从杂志中剪下适当数量的字符以形成勒索字条。我已经设法将字符和字符的出现次数添加到 hashMap,但我如何比较这两个 hashMap 以确定我有足够的字母。任何指导将不胜感激。

杂志 = {g=2, =14, d=2, e=2, a=4, n=1, o=5, l=4, m=1, .=1, k=1, I =2, h=2, i=6, w=1, T=1, u=1, t=2, s=3, r=1, y=2}赎金 = {w=1, =3, o=1, l=4, k=1, I=1, y=1, i=2}

String mag = "this is what I said Im going to do. i really like you a lot";
String ransom = "i will kill you";

Map<Character,Integer> map = new HashMap<Character,Integer>();
Map<Character,Integer> ransomMap = new HashMap<Character,Integer>();

for(int i = 0; i < mag.length() -1; i++)
{
char c = mag.charAt(i);
if(!map.containsKey(c))
map.put(c, 1);
else{
int value = map.get(c);
map.put(c,++value);
}
}

System.out.println(map);

for(int i = 0; i < ransom.length()-1; i++ )
{
char c = ransom.charAt(i);
if(!ransomMap.containsKey(c))
ransomMap.put(c,1);
else
{
int value = (ransomMap.get(c));
ransomMap.put(c,++value);
}
}
System.out.println(ransomMap);
}

最佳答案

检查赎金记录中的每个字母,看看报纸上是否有足够的字母:

boolean enoughLetters(Map<Character, Integer> magMap, Map<Character,Integer> ransomMap) {
for( Entry<Character, Integer> e : ransomMap.entrySet() ) {
Character letter = e.getKey();
Integer available = magMap.get(letter);
if (available == null || e.getValue() > available) return false;
}
return true;
}

关于java - 比较 hashMap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15578453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com