383. Ransom Note

xiaoxiao2021-02-28  132

原本打算使用list的<运算符,因为set具有比较两个set是否是包含关系的<运算符,但是list的<运算符比较的是list中的相应元素的大小,第一个元素优先比较,如果第一个元素是相等的,则比较第二个元素

class Solution(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ r = list(ransomNote) m = list(magazine) d= dict() for i in range(len(m)): if m[i] in d: d[m[i]] += 1 else: d[m[i]] = 1 for i in range(len(r)): if r[i] in d: if d[r[i]] > 0: d[r[i]] -= 1 else: return False else: return False return True

将magazine中的字母按照字母作为key,出现的次数作为value的形式存储在dict中,ransomNote中的字母挨个去dict中检查,当dict中没有相应字母或者相应字母的次数已经小于零的时候,返回False即可

使用collections.Counter

Counter的介绍: http://www.2cto.com/kf/201303/196938.html

def canConstruct(self,ransomNote,magazine): return not collections.Counter(ransomNote) - collections.Counter(magazine)
转载请注明原文地址: https://www.6miu.com/read-41313.html

最新回复(0)