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
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode 383. Ransom Note
- 383. Ransom Note*
- 383. Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- 383. Ransom Note
- 383.[LeetCode]Ransom Note
- 383. Ransom Note
- 383. Ransom Note【E】
- leetcode 383. Ransom Note
- 383. Ransom Note
- 383. Ransom Note
- leetcode 383. Ransom Note
- Leetcode 383. Ransom Note
- 【leetcode】383. Ransom Note
- Leetcode 383. Ransom Note
- unity游戏性能优化之cpu优化第二节--对象池技术的介绍
- Leetcode 268. Missing Number
- ubuntu下完美安装pyenv+virtualenv
- 高仿网易照片浏览器,支持本地及网络相册!
- 计时器Timer
- 383. Ransom Note
- 只要五分钟,让你成功接入Twitter的第三方登录
- 交换机基本配置
- iOS 地图定位偏差
- 把时间当成朋友观后感
- android 获取路径目录方法以及判断目录是否存在,创建目录
- MFC浏览文件夹、文件、路径
- [代码]基于RNN的文本生成算法
- cell.accessoryType不显示