我在练习一些面试问题,但不知道如何比较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}
杂志 = {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);
}
available == null
。 - Andrew MaocontainsKey()
来避免像我一样的空值检查:if (!magMap.containsKey(letter) || magMap.get(letter).getValue() > available) return false;
- achcontainsKey()
。这可能是过早的优化,但这已经成为了我的习惯。 :) - Andrew Mao