美文网首页
字符串 Leetcode 383 赎金信

字符串 Leetcode 383 赎金信

作者: 禾木清清 | 来源:发表于2019-11-28 15:14 被阅读0次

    题目

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

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

    注意:

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/ransom-note
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路

    需要从杂志上找到对应的字母拼接成信,所以杂志上对应字母的频率要高于随机信。只要统计和判断频率就可以。

    代码

    class Solution:
        def canConstruct(self, ransomNote: str, magazine: str) -> bool:
            randomCounter = collections.Counter(ransomNote)
            magazineCounter = collections.Counter(magazine)
    
            for key in randomCounter:
                if randomCounter.get(key,0) <= magazineCounter.get(key,0):
                    continue
                else:
                    return False
            return True
    

    相关文章

      网友评论

          本文标题:字符串 Leetcode 383 赎金信

          本文链接:https://www.haomeiwen.com/subject/gpsbwctx.html