substring-with-concatenation-of-all-words

来源:互联网 发布:tcp ip的网络层 编辑:程序博客网 时间:2024/06/06 06:55

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 resa = ["foo", "bar","the"]print findSubstring("barfoothefoobarmanthe", a)


原创粉丝点击