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") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("aa", "aab") -> true
题目思路就是将note和magzine的字符串用Counter来计数, 针对每个note的每个字符, 如果d_m[c] > d_note[c], 就可行, 否则False
Code
class Solution: def ransomNote(self, note, magzine): d_note, d_mag = collections.Counter(note), collections.Counter(magzine) for k in d_note: if d_note[k] > d_mag[k]: return False return True