30. Substring with Concatenation of All Words

Find All Anagrams in a String 基本上是一道题,character换成了word而已。

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        if not s or not words:
            return []
        res = []
        freqT = Counter(words)
        lenW = len(words[0])
        lenT = lenW*len(words)
        for i in range(len(s)-lenT+1):
            window = s[i:i+lenT]
            freqW = dict()
            for j in range(0, len(window), lenW):
                word = window[j:j+lenW]
                if word not in freqT: break
                else:
                    freqW[word] = freqW.get(word, 0) + 1
            if freqW == freqT:
                res.append(i)
        return res

Last updated

Was this helpful?