383 赎金信
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
用字典存储magazine 中的字母及出现次数,然后如果ransomNote中的字符在字典中,就每次减1,最后看字典中有没有出现次数小于0 的键,有的话就是不能组成,没有的话就是可以组成。
from collections import defaultdict
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(magazine) < len(ransomNote):return False
res = defaultdict(int)
for i in magazine:
res[i] += 1
for j in ransomNote:
res[j] -= 1
if res[j] < 0:return False
return True