383. Ransom Note [easy] (Python)
来源:互联网 发布:湖北软件开发公司 编辑:程序博客网 时间:2024/05/01 23:52
题目链接
https://leetcode.com/problems/ransom-note/
题目原文
> 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
题目翻译
给定一个勒索信字符串,和一个包含所有杂志里字符的字符串,写一个函数,当该信可以被所有杂志里字符构成时返回true,否则返回false。杂志字符串里每个字符只能使用一次。
注意:假定两个字符串都只包含小写字符。
思路方法
思路一
计算两个字符串每个字母出现的次数再比较即可。可以用数组或字典保存每个字母出现的次数,对于两个字符串分别用加法和减法统计字母出现次数。下面的代码用了数组。
代码
class Solution(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ if len(ransomNote) > len(magazine): return False letters = [0] * 26 for c in magazine: letters[ord(c) - 97] += 1 for c in ransomNote: letters[ord(c) - 97] -= 1 if letters[ord(c) - 97] < 0: return False return True
思路二
与思路一相同,不过用的字典。
代码
class Solution(object): def canConstruct(self, ransomNote, magazine): """ :type ransomNote: str :type magazine: str :rtype: bool """ if len(ransomNote) > len(magazine): return False letters = {} for c in magazine: letters[c] = letters[c] + 1 if c in letters else 1 for c in ransomNote: if c not in letters: return False letters[c] -= 1 if letters[c] < 0: return False return True
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52387920
- 383. Ransom Note [easy] (Python)
- 383. Ransom Note 难度:easy
- Leetcode 383. Ransom Note (Easy) (cpp)
- 383.leetcode Ransom Note(easy)[字符统计]
- LeetCode解题报告 383. Ransom Note [easy]
- leetcode383[easy]--- Ransom Note
- leetcode 383. Ransom Note python
- LeetCode-Easy部分中标签为String 383. Ransom Note
- 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
- 二叉树的实现
- Android网络请求 ------ Volley的使用
- 分布函数和概率密度函数的区别
- cocos2d-JS 屏幕适配(5种适配模式)
- StringUtils中isEmpty 和isBlank的区别
- 383. Ransom Note [easy] (Python)
- 进程同步
- Bolts-Android
- 初识基于 Web 的可视化编程工具Google Blockly
- 一篇关于apache commons类库的详解
- HTML5初学 元素、属性、格式化、样式、链接、表格、列表、快、布局(div和table)
- 控件——ListView
- String类Demo
- 解析json之net.sf.json