383.赎金信
一、直方图法
根据题意ransomNote的所有字符magazine中都必须出现,且只能用一次 将ransomNote的字符统计频率,再遍历magazine,遇到一个字符就将其频率减一。最后看每个字符频率是否<=0,则说明符合
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
cnt = [0] * 26
for c in ransomNote:
cnt[ord(c) - ord('a')] += 1
for c in magazine:
cnt[ord(c) - ord('a')] -= 1
for num in cnt:
if num > 0:
return False
return True
最后更新于