LeetCode-Python-383. 赎金信

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)

注意:

你可以假设两个字符串均只含有小写字母。

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

思路:

分别统计一下两个字符串的字符数量,对于ransom里的每个字符来说,如果同一字符在magazine里出现的次数大于在ransom里出现的次数,就代表可以构成这个ransom。

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        
        r = collections.Counter(ransomNote)
        m = collections.Counter(magazine)
        
        for key in r:
            if m.get(key, 0):
                if m[key] < r[key]:
                    return False
            else:
                return False
            
        return True

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/88372817
今日推荐