Leetcode#383. 赎金信

解题思路:

  • 将问题简单化,即两个字符串中字母数量相比,若第二个字符串中的字母数量及字母种类均大于等于第一个字符串,那就返回True,否则返回False

python实现如下:

class Solution:
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        dict1 = {}
        dict2 = {}
        for item in ransomNote:
            if item not in dict1:
                dict1[item] = 1
            else:
                dict1[item] += 1
        for item in magazine:
            if item not in dict2:
                dict2[item] = 1
            else:
                dict2[item] += 1

        for key in dict1.keys():
            if key not in dict2:
                return False
            if dict2[key] < dict1[key]:
                return False

        return True

你可能感兴趣的:(======,Leetcode,=======)