You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []
首先看题中的两个例子,words里有重复的词,为了处理这种情况,我们要记录每个词在s中出现的次数。
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
ans=[]
wordsCount={}
for word in words:
if word in wordsCount:
wordsCount[word]+=1
else:
wordsCount[word]=1
if len(s)==0 or len(words)==0:
return []
for i in range(len(s)-len(words)*len(words[0])+1):
wordsFind={}
flag=0
for k in range(len(words)):
sub=s[i+k*len(words[0]):i+(k+1)*len(words[0])]
if sub in wordsCount:
if sub in wordsFind:
wordsFind[sub]+=1
else:
wordsFind[sub]=1
else:
flag=1
break
if wordsFind[sub]>wordsCount[sub]:
flag=1
break
if flag==0:
ans.append(i)
return ans
使用两个字典来保存words的数量,第一个wordsCount用来记录words中每个word出现的次数。然后s从开始遍历,每次检查的词长度为word的长度。sub如果在words中没有的话就跳出继续检查下一个,有的话就更新wordsFind,wordsFind记录的是s中word词出现的数量,每更新完一个词后要检查有没有超过words中这个词的数量。