You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S:"barfoothefoobarman"
L:["foo", "bar"]
You should return the indices:[0,9].
(order does not matter).
def findSubstring(S, L):
map = {}
for i in L:
if i not in map:
map[i] = 1
else:
map[i] += 1
begin = 0
end = 0
le = len(L[0])
count = len(L)
res = []
while end < len(S)-le + 1:
if S[end:end+le] not in map:
map[S[end:end + le]] = -1
if map[S[end:end + le]] > 0:
map[S[end:end + le]] -= 1
count -= 1
end = end + le
else:
end += 1
while count == 0:
if map[S[begin:begin+le]] == 0:
res.append(begin)
begin = end
count = len(L)
for i in L:
if i not in map:
map[i] = 1
else:
map[i] += 1
else:
begin += 1
return res
a = ["foo", "bar","the"]
print findSubstring("barfoothefoobarmanthe", a)
class S: def __init__(self): pass @staticmethod def find_substring(s, words): if len(s) < len(words)*len(words[0]): return [] word_len, word_num = len(words[0]), len(words) word_dic = {} for i in words: if i not in word_dic: word_dic[i] = 1 else: word_dic[i] += 1 result = [] for i in range(len(s)+1-word_len*word_num): tmp_dic, j = {}, 0 while j < word_num: word = s[i+j*word_len:i+j*word_len+word_len] if word not in word_dic: break if word not in tmp_dic: tmp_dic[word] = 1 else: tmp_dic[word] += 1 if tmp_dic[word] > word_dic[word]: break j += 1 if j == word_num: result.append(i) return result s = S() print(s.find_substring('ashjkdfghjkl', ['dfg', 'hjk']))