码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 383. Ransom Note_Easy tag: Hash Table

时间:2018-08-15 01:20:24      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:bsp   str   table   counter   let   letters   ini   hat   collect   

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

标签:bsp   str   table   counter   let   letters   ini   hat   collect   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9479083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!