leetcode383.赎金信

171 阅读1分钟

383.赎金信

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

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

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

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

(a,b两个字符串,利用b字符串中的字母组成a,且b中每个字母仅可使用一次)

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ran = collections.Counter(ransomNote)
        mag = collections.Counter(magazine)
        return not ran - mag
# 利用Python的collections.Counter类统计字符个数,然后做差
# 只需要 magazines字符个数都大于等于 ransom里字符个数即可。
# 所以对ran-mag取非