【Leetcode_总结】383. 赎金信 - python

Q:

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

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

注意:

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

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

链接:https://leetcode-cn.com/problems/ransom-note/description/

思路:判断条件 如果子串统计每个字符的字符频小于母串,则为False

代码:

class Solution:
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        from collections import Counter
        mag_dic = Counter(magazine)
        ran_dic = Counter(ransomNote)
        for r in ran_dic:
            if r in mag_dic:
                if ran_dic[r] > mag_dic[r]:
                    return False
            else:
                return False
        return True

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86345012