383. 赎金信 - 力扣(LeetCode) (leetcode-cn.com)https://leetcode-cn.com/problems/ransom-note/我是用HashMap做的,实际上用长度26的数组做也可以,应该会更快。
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character,Integer> map = new HashMap<>();
for(char c:magazine.toCharArray()){
if (map.containsKey(c))
map.put(c,map.get(c)+1);
else
map.put(c,1);
}
for (char c:ransomNote.toCharArray()){
if(map.containsKey(c)){
if(map.get(c)==0)
return false;
map.put(c,map.get(c)-1);
}else
return false;
}
return true;
}
}