题目链接
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") -> false
canConstruct("aa", "ab") -> false
canConstruct("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