383. Ransom Note

来源:互联网 发布:淘宝uv pv 编辑:程序博客网 时间:2024/06/07 06:04

题意: Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:
You may assume that both strings contain only lowercase letters.

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

思路:这题其实题意很模糊,它的意思就是后一个字符串是不是包含前一个字符串需要的所有字符个数,所以还是用建字典,然后从里面减,有小于0或键值不存在就返回False:

class Solution(object):    def canConstruct(self, ransomNote, magazine):        """        :type ransomNote: str        :type magazine: str        :rtype: bool        """        ans = {}        for i in magazine:            ans[i] = ans.get(i,0)+1        for i in ransomNote:            if i in ans.keys():                ans[i] -= 1                if ans[i] < 0:                    return False            else:                return False        return True

当然也可以用collections.Counter来直接建字典哈希表:

def canConstruct(self, ransomNote, magazine):    return not collections.Counter(ransomNote) - collections.Counter(magazine)
0 0