383. Ransom Note

来源:互联网 发布:sql中like用法 编辑:程序博客网 时间:2024/06/01 07:33

原本打算使用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)
0 0