030 Substring with Concatenation of All Words

030 Substring with Concatenation of All Words 

用一个dictiionary来记录当前对应还有多少需要match的word。 dict.copy()用来copy dictionary.

from collections import defaultdict
class Solution:
    # @param {string} s
    # @param {string[]} words
    # @return {integer[]}
    def findSubstring(self, s, words):
        d = defaultdict(int)
        m = len(words[0])
        for w in words:
            d[w] += 1
        ans = []
        for i in range(0,m):
            tmp = [s[i+j:i+m+j] for j in range(0, len(s), m)]
            dic = dict.copy(d)
            start = 0
            for j in range(0, len(words)-1):
                if tmp[j] in words:
                    dic[tmp[j]] -= 1
            for j in range(len(words)-1, len(tmp)):
                if tmp[j] in dic:
                    dic[tmp[j]] -= 1
                if dic.values() == ([0] * len(dic)):
                    ans.append(m*(j-len(words)+1) + i)
                if tmp[j-len(words)+1] in dic:
                    dic[tmp[j-len(words)+1]] += 1
        return ans

 

posted @ 2015-07-17 14:32  dapanshe  阅读(106)  评论(0编辑  收藏  举报