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: []
s = "barfoothefoobarman"
words = ["foo", "bar"]
单词长度: wordLen = 3
单词个数: wordNum = 2
字符串长度: len = 17
Words Map = {[foo:1], [bar:1]}
i=0
子串 Map = {}
| b a r f o o t h e f o o b a r m a n
当前子串: "barfoo", 满足条件, res=[0]
i=1
子串 Map = {}
b | a r f o o t h e f o o b a r m a n
当前子串: "arfoot", 不满足条件, 退出, 移到下一个, res=[0]
i=2
子串 Map = {}
b a | r f o o t h e f o o b a r m a n
当前子串: "rfooth", 不满足条件, 退出, 移到下一个, res=[0]
.
.
.
i=9
子串 Map = {}
b a r f o o t h e | f o o b a r m a n
当前子串: "foobar", 满足条件, res=[0, 9]
.
.
.
i=13, 退出, 剩余子串长度不满足. res=[0, 9]
from typing import Listimport collectionsclassSolution:deffindSubstring(self,s:str,words: List[str]) -> List[int]:ifnot s ornot words:return [] w_num =len(words) w_len =len(words[0]) w_count = collections.Counter(words) res = []for i inrange(w_len): temp_count = collections.defaultdict(int) left = ifor right inrange(i, len(s) - w_len +1, w_len): temp_word = s[right: right + w_len]if w_count[temp_word]>0: temp_count[temp_word]+=1while temp_count[temp_word]> w_count[temp_word]: temp_count[s[left: left + w_len]]-=1 left += w_lenif right + w_len - left == w_num * w_len: res.append(left) temp_count[s[left: left + w_len]]-=1 left += w_lenelse: left = right + w_len temp_count.clear()return res