题目描述
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
思路与算法
使用哈希表(字典)来统计 magazine 中每个字符出现的次数。
对于 ransomNote 中的每个字符,查看 magazine 中是否有足够的字符。每次使用一个字符后,减少 magazine 中该字符的数量。
如果遍历完 ransomNote 中的字符,且 magazine 中有足够的字符,那么返回 True;否则,返回 False。
代码
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
# 统计 magazine 中每个字符的频率
magazine_count = Counter(magazine)
for char in ransomNote:
if magazine_count[char] == 0:
return False
magazine_count[char] -= 1
return True
总结
- Python 内置模块 collections.Counter 是一个非常适合频数统计的工具,能够方便地对字符串、列表等进行计数。其返回的字典可以直接使用键来查找字符的频次。