<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p>

<p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p>

<ul>
	<li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li>
</ul>

<p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p>

<p><strong>Output:</strong> <span class="example-io">[0,9]</span></p>

<p><strong>Explanation:</strong></p>

<p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br />
The substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p>
</div>

<p><strong class="example">Example 2:</strong></p>

<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p>

<p><strong>Output:</strong> <span class="example-io">[]</span></p>

<p><strong>Explanation:</strong></p>

<p>There is no concatenated substring.</p>
</div>

<p><strong class="example">Example 3:</strong></p>

<div class="example-block">
<p><strong>Input:</strong> <span class="example-io">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p>

<p><strong>Output:</strong> <span class="example-io">[6,9,12]</span></p>

<p><strong>Explanation:</strong></p>

<p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br />
The substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br />
The substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p>
</div>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= words.length &lt;= 5000</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 30</code></li>
	<li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li>
</ul>

import re
from collections import Counter
from typing import List

'''
* 단순히 Counter를 만들어놓고 비교하면 쉬울 텐데
barfoo -> ['bar', 'foo'] -> Counter와 비교({bar:1, foo:1})

* 그러나 제약 상 비효율적이기 때문에 조건을 따져야 함
* 처음부터 부분문자열로 시작하고, 필요한 단어를 모두 충족해야 함
'''
class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        if not s or not words:
            return []

        N = len(words[0])
        cnt = len(words)
        total = N * cnt
        word_counter = Counter(words)

        def check(substr):
            '''
            concat 여부 체크
            ex) barfoo -> ['bar', 'foo'] -> Counter와 비교({bar:1, foo:1}) -> True
            '''
            substr_words = [substr[i:i+N] for i in range(0, len(substr), N)]
            return Counter(substr_words) == word_counter

        '''
        TODO: 부분문자열 블록 단위로 패턴을 파악해야 함 (barfoo -> ['bar', 'foo'])
        * (?=X)Y: X문자열로 시작하는 Y패턴 -> 'XY'
        * (A|B|C): 셋 중 하나라도 만족하면 True
        * (P){I, J}: P 패턴이 최소 I번, 최대 J번 등장해야 함(공란 시 0, 무한) 
        '''
        pattern = f"(?=({'|'.join(words)}){{1,{cnt}}})"
        # -> words 리스트에 담겨있는 부분문자열 블록을 최소한 1개 또는 최대한 단어 개수만큼만 탐색하겠음
        
        ret = []
        for match in re.finditer(pattern, s): 
            start = match.start()  # 조건이 충족하는 시작 인덱스
            if start + total <= len(s):
                substr = s[start: start+total]
                if check(substr):
                    ret.append(start)

        '''
        Ex) s=barfoothefoobarman, [bar foo]
        1째 start=0, substr=barfoo->True
        2째 start=3, substr=foothe->False
        3째 start=9, substr=foobar->True
        '''
        return ret
19600