Substring with Concatenation of All Words

问题:给定一个字符串s和一个由多个等长字符串组成的列表words,输出列表中的字符串组成的整体在s中的所有可能的位置

示例:

输入:s = "abcmmedfrgaqwedfrmme"   words=["mme","dfr"]

输出:[3,14]

解决思路:从0开始对words进行遍历,判断长度为w_len(words中每个字符串的长度)的子串是否与words中的某个字符串相同,相同,则继续往后判断,不同则进行下一次遍历。本问题的关键是遍历的范围不能直接为s的长度,而需要考虑words中的字符串总长度

Python代码:

class Solution(object):
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        if not words:
            return []
        w_len = len(words[0])       
        all_len = w_len*len(words)
        
        out = []
        word_count = collections.Counter(words)
        
        for i in range(len(s)-all_len+1):
            sub_i = s[i:i+w_len]
            if sub_i in word_count:
                j = i + w_len
                wc = word_count.copy()
                wc[sub_i] -= 1
                while j <= all_len + i-w_len:
                    sub = s[j:j+w_len]
                    if sub in wc and wc[sub]:
                        wc[sub] -= 1
                        j += w_lenelse:
                        break
                if not sum(wc.values()):
                    out.append(i)                  
        return out
原文地址:https://www.cnblogs.com/wenqinchao/p/10688959.html