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 “barfoo” 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的全排列,所以需要一个hashmap记录下words当中每一个Word的出现次数。然后从left位置开始遍历,如果right位置对应的字符串在words当中出现过,并且此时在hashmap中的值仍然大于1,那我们就把right后移,并且将hash_map中对应的word减1。如果right位置在words中出现过,但是其在hash_map当中的值为0或者right位置在words中没有出现,那就将left后移一个位置,重新开始。具体实现代码如下:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
if not s or not words:
return []
solution = []
word_dict = {}
word_dict = dict(collections.Counter(words))
length = len(words[0])
for index in range(len(s)-length*len(words)+1):
temp_dict = word_dict.copy()
for i in range(len(words)):
new_word = s[index+length*i: index+length*i+length]
if new_word in temp_dict:
if temp_dict[new_word] > 1:
temp_dict[new_word] -= 1
else:
temp_dict.pop(new_word)
else:
break
if not temp_dict:
solution.append(index)
return solution