码迷,mamicode.com
首页 > 其他好文 > 详细

030 Substring with Concatenation of All Words

时间:2015-07-17 15:49:29      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

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

 

030 Substring with Concatenation of All Words

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4654396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!