class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if(ransomNote.length()>magazine.length()){
return false;
}
HashMap<Character,Integer> hm=new HashMap<>();
for(int i=0;i<magazine.length();i++){
hm.put(magazine.charAt(i),hm.getOrDefault(magazine.charAt(i),0)+1);
}
for(int i=0;i<ransomNote.length();i++){
if(hm.containsKey(ransomNote.charAt(i))==false){
return false;
}
hm.put(ransomNote.charAt(i),hm.get(ransomNote.charAt(i))-1);
if(hm.get(ransomNote.charAt(i))==-1){
return false;
}
}
return true;
}
}
class Solution(object):
def canConstruct(self, ransomNote, magazine):
if len(ransomNote)>len(magazine):
return False
hm=defaultdict(int)
for i in magazine:
hm[i]+=1
for i in ransomNote:
if not hm.has_key(i):
return False
hm[i]-=1
if hm[i]==-1:
return False
return True
标签:ransomNote,False,26,return,canConstruct,magazine,hm,赎金
From: https://blog.csdn.net/Runner__Binger/article/details/142266237