问题描述:
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
注意:
你可以假设两个字符串均只含有小写字母。
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
方法:
from collections import Counter
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
dic1 = Counter(ransomNote)
dic2 = Counter(magazine)
#dic1,dic2 = map(Counter,(ransomNote,magazine)
for key in dic1.keys():
if key in dic2 and dic2[key] <dic1[key] or key not in dic2:
return False
return True
官方:set(ransomNote) 建立dic存放ransomNote词频计数,用magazine.count(val) 和 dic中的val做对比
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
x=set(i for i in ransomNote)
dic={}
for i in x:
dic[i]=ransomNote.count(i)
for k,v in dic.items():
if magazine.count(k)<v:
return False
return True
2018-09-28 15:55:36