给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false
思路:
和上一条按字符出现的频率的顺序输出的思路差不多。
用一个字典存下magazine中出现的字母以及相应的次数。
然后再对ransom进行循环。对于每个字符判断是否在字典中,如果不在则返回false,若在字典中但出现的次数已经归零,也返回false,否则则对字典中相应的字符出现次数减1.
def canConstruct(ransomNote, magazine):
if ransomNote == "" and magazine == "":
return True
table = {}
for s in magazine:
if s in table.keys():
table[s] += 1
else:
table[s] = 1
for t in ransomNote:
if t not in table.keys():
return False
elif table[t] < 1:
return False
else:
table[t] -= 1
return True
ran = "aa"
ma = "ab"
print(canConstruct(ran, ma))