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:
1 2 3 4 5 6
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.
classSolution: deffindSubstring(self, s, words): ifnot s or words==[]: return [] lenstr=len(s) lenword=len(words[0]) lensubstr=len(words)*lenword times={} for word in words: if word in times: times[word]+=1 else: times[word]=1 ans=[] for i inrange(min(lenword,lenstr-lensubstr+1)): # lenstr挨个来,所以只需lenword次即可 self.findAnswer(i,lenstr,lenword,lensubstr,s,times,ans) return ans deffindAnswer(self,strstart,lenstr,lenword,lensubstr,s,times,ans): wordstart=strstart curr={} while strstart+lensubstr<=lenstr: word=s[wordstart:wordstart+lenword] wordstart+=lenword if word notin times: strstart=wordstart curr.clear() else: if word in curr: curr[word]+=1 else: curr[word]=1 # 如果大于已有的,尝试删除一些内容。 while curr[word]>times[word]: curr[s[strstart:strstart+lenword]]-=1 strstart+=lenword if wordstart-strstart==lensubstr: ans.append(strstart)
if __name__ == "__main__": test = Solution() s, words = 'barfoothefoobarman', ['foo', 'bar'] print(test.findSubstring(s, words))