题目
思路分析1
题目要求:找出 由words数组组成的字符串(每一个元素word等长),在字符转s中的位置
- 数组words生成的字典dic2
- 遍历字符串,从头开始判断长度为lenwords的字符串 生成的字典dic1
- 如果dic1 与 dic2 相同,说明找到
代码展示1
def findSubstring(self, s: str, words):
if s =="" or words ==[]:
return[]
res =[]
lenwords = len(words[0]*len(words))
#数组words生成的字典dic2
dic2 = self.help2(words)
for i in range(len(s)-lenwords+1):
#从头开始判断长度为lenwords的字符串 生成的字典dic1
dic1 = self.help1(s[i:i+lenwords],len(words[0]))
if dic1==dic2:
res.append(i)
return res
#通过 字符串str 和每一个单词的长度interval,生成字典
def help1(self,str,interval):
dic = {}
for i in range(0,len(str)-interval+1,interval):
if str[i:i+interval] not in dic:
dic[str[i:i+interval]] = 1
else:
dic[str[i:i+interval]] += 1
return dic
#通过数组words 生成字典
def help2(self,words):
dic ={}
for i in words:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
return dic
思路分析2
题目要求:找出 由words数组组成的字符串(每一个元素word等长),在字符转s中的位置
- 对数组words排序
- 遍历字符串,对长度为totallen的字符串,拆成数组,排序
- 如果 排好序的数组 相同,说明找到
代码展示2
def findSubstring2(self, s: str, words):
if s =="" or words ==[]:
return[]
res =[]
#对单词数组进行排序
words = sorted(words)
totallen = len(words[0])*len(words)
wordlen = len(words[0])
for i in range(len(s)-totallen+1):
temp = []
#对长度为totallen的字符串,拆成数组
for j in range(0,totallen,wordlen):
temp.append(s[i+j:i+j+wordlen])
temp = sorted(temp)
if temp == words:
res.append(i)
return res