题目在这:https://leetcode-cn.com/problems/ransom-note/
思路分析:
题目中明确要求:杂志字符串中的每个字符只能在赎金信字符串中使用一次。
我们使用哈希表。将杂志字符串中元素作为key,出现的次数作为val。
然后遍历赎金信。出现一次,则使哈希表中对应key的val减1。 如果出现了负数val,则表示失败。
完整代码:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
from collections import Counter
hash_map_maga = Counter(magazine)
for i in ransomNote:
if i in hash_map_maga:
hash_map_maga[i] -=1
if hash_map_maga[i] <0:
return False
else:
print('false')
return False
return True