Skip to content

383 ransom note

383. Ransom Note

题目: https://leetcode.com/problems/ransom-note/

难度 : Easy

略微想了一下,用了一个dictionary来存magazine里面的单字出现的个数,然后来对应check是否可以用来组成ransomNote

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        maps = {}
        for i in magazine:
            if i in maps:
                maps[i] += 1
            else:
                maps[i] = 1
        for i in ransomNote:
            if i not in maps:
                return False
            else:
                maps[i] -= 1
                if maps[i] < 0:
                    return False
        return True

解法2:

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        magCounter = collections.Counter(magazine)
        ranCounter = collections.Counter(ransomNote)
        for k in ranCounter:
            if ranCounter.get(k) > magCounter.get(k):
                return False
        return True


回到顶部