1. 程式人生 > >給定一個字符串s和一個由多個等長字符串組成的列表words,輸出列表中的字符串組成的整體在s中的所有可能的位置

給定一個字符串s和一個由多個等長字符串組成的列表words,輸出列表中的字符串組成的整體在s中的所有可能的位置

bst pytho span string 輸入 列表 所有 sum pen

示例:

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

輸出:[3,14]

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_len pre = sub
else: break if not sum(wc.values()): out.append(i) return out

給定一個字符串s和一個由多個等長字符串組成的列表words,輸出列表中的字符串組成的整體在s中的所有可能的位置