题目描述
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
假设两个字符串均只含有小写字母。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
示例
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
解答
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
# 统计ransomNote中的字符及其出现次数
ransom_dict = dict()
for char in ransomNote:
if char not in ransom_dict.keys():
ransom_dict[char] = 0
ransom_dict[char] = ransom_dict[char] + 1
# 统计magazine中的字符及其出现次数
maga_dict = dict()
for char in magazine:
if char not in maga_dict.keys():
maga_dict[char] = 0
maga_dict[char] = maga_dict[char] + 1
for char,count in ransom_dict.items():
# ransomNote中的字符没有出现在magazine中,返回false
if char not in maga_dict.keys():
return False
# ransomNote中的字符出现在magazine中,但是ransomNote中的数量比magazine中的多,返回false
elif count>maga_dict[char]:
return False
return True