[LeetCode] 383. Ransom Note_Easy tag: Hash Table

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 383. Ransom Note_Easy tag: Hash Table相关的知识,希望对你有一定的参考价值。

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

题目思路就是将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

 


以上是关于[LeetCode] 383. Ransom Note_Easy tag: Hash Table的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 383. Ransom Note

LeetCode(383)Ransom Note

LeetCode 383 Ransom Note

LeetCode 383 Ransom Note

Leetcode 383 Ransom Note

[leetcode-383-Ransom Note]