- Substring with Concatenation of All Words Hard
703
1086
Add to List
Share 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: []
思路:滑动窗口 subStr=s[i:i+len(words)*len(words[0])] words存入hashMap,dic[wors[i]]+=1
代码:python3
class Solution:
def findSubstring(self, s, words) :
if not s or not words or len(s)==0 or len(words)==0:return []
dic={}
res=[]
for w in words:
if w not in dic:
dic[w]=1
else:
dic[w]+=1
lw=len(words)
lws=len(words[0])
ls=len(s)
for i in range(0,ls-lw*lws+1):
copDic=dict(dic)
subs=s[i:i+lw*lws]
for j in range(lw):
ss=subs[j*lws:j*lws+lws]
print(ss)
if ss in copDic:
if copDic[ss]==1:
del copDic[ss]
else:
copDic[ss]-=1
else:
break
if not copDic:res.append(i)
return res
if __name__ == '__main__':
print(Solution().findSubstring("barfoothefoobarman",["foo","bar"]))