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
思路: 这道题就是判断第一个字符串的每一个字符,是否都在第二个字符串中存在.(需要比较重复出现次数)
所以用set()找出有哪些字符,用count()找出每个字符存在几个,然后与第二个字符串比较即可.
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
for i in set(ransomNote):
if ransomNote.count(i) > magazine.count(i):
return False
return True

本文介绍了一种解决勒索信问题的字符串匹配算法。该算法通过比较两个字符串中字符的出现次数,判断第一个字符串(勒索信)是否能由第二个字符串(杂志文章)中的字符构造而成。详细解析了算法思路及Python实现代码。
461

被折叠的 条评论
为什么被折叠?



