题目

383. Ransom Note
简单来说,就是判断a字符串能够使用b字符串中的字母来构造。

我的代码

思路就是使用计数器,计算每个字符的出现次数,比较其能否使用:

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        magazinecnt=collections.Counter()
        notecnt=collections.Counter()
        for i in ransomNote:
             notecnt[i]+=1
        for i in magazine:
            magazinecnt[i]+=1
        for i in notecnt:
            if notecnt[i]>magazinecnt[i]:
                return False
        return True

高效/简单的代码:

其实,直接使用计数函数计数就完事了

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        for _ in set(ransomNote):
            if ransomNote.count(_) > magazine.count(_):
                return False
        return True

相关文章: