欢乐力扣:赎金信- 代码

时间:2025-02-23 08:32:58
class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        from collections import defaultdict
        # 构造字典存储字符串的字母和数量
        ref_dic = defaultdict(int)
        for char in magazine:
            ref_dic[char] +=1
        # 遍历
        for char in ransomNote:
            if char in ref_dic:
                ref_dic[char] -=1  
                # 如果减到0了,则需要彻底移除这个key
                if ref_dic[char] == 0:
                    del ref_dic[char] 
            else:
                return False 
        return True