一、问题描述
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
注意:
你可以假设两个字符串均只含有小写字母。
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
二、代码和思路
1.构建一个跟magazine等长的且元素全为0的列表
2.如果列表中的元素被ransomNote引用后则设置该位置的元素为1
3.循环遍历查找ransomNote中的元素结合magazine_list
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
m,n=len(magazine),len(ransomNote)
magazine_list=[0]*m
for st in ransomNote:
i=0
while i<m and (magazine[i] != st or magazine_list[i]==1):
i += 1
if i==m:return False
magazine_list[i]=1
return True
三、运行结果
算法复杂度有点高应该是O(m*n)