Day3-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.
字符串匹配问题,magazine的字符串中的字符是否能组成ransomNote的字符。有一个限制条件是magazine中的字符和ransomNote中的字符是一一对应的,也就是不存在多对一的关系,重复的情况是不存在的。就是例子中第二个那种,ransomNote中有两个a,magazine中也得有两个a.
Example:
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
解法一:
以空间换时间,我们设置两个字典分别存储两个字符串中字符出现的次数,然后遍历ransom字典,如果该元素在magazine字典中没有返回False,如果在magazine字典中出现的次数少于ransom字典的次数返回False.
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ran_dict = {}
magazine_dict = {}
for i in ransomNote:
if i in ran_dict:
ran_dict[i] += 1
else:
ran_dict[i] = 0
for i in magazine:
if i in magazine_dict:
magazine_dict[i] += 1
else:
magazine_dict[i] = 0
for i in ran_dict:
if i in magazine_dict:
if magazine_dict[i] < ran_dict[i]:
return False
else:
return False
return True
m-len(ransom),n-len(magazine)时间复杂度维O(m).空间复杂度维O(n + m).
解法二:
和上面那种一样,只不过用到了python中collection中的counter类,它是字典的子类,主要是实现计数功能,我们用他来对两个字符串分别计数,然后再相减取反就可以了,相减返回的是值为正值的元素,这样如果magazine的元素次数比ransom的少,返回的为正值我们就取反为false。
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransomCnt = collections.Counter(ransomNote)
print(ransomCnt)
magazineCnt = collections.Counter(magazine)
print(magazineCnt)
print(ransomCnt - magazineCnt)
return not ransomCnt - magazineCnt
本文探讨了如何判断一个字符串是否能由另一个字符串中的字符组成,重点介绍了两种解法:一是通过字典统计字符频率,二是利用Python的collections.Counter类进行高效计算。
1263

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



