substring-with-concatenation-of-all-words

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']))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值