class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
answer = []
n = len(s)
sorted_words = sorted(words)
word_size = len(words[0])
start = 0
end = word_size * len(words)
while end <= n:
substring_words = [s[i:i + word_size] for i in range(start, end, word_size)]
if sorted(substring_words) == sorted_words:
answer.append(start)
start += 1
end += 1
return answer

위와 같이 통과는 하지만 상당히 긴 실행시간을 소요하기 때문에 정렬이 아닌 다른 방법을 사용한 풀이를 생각해보자
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
answer = []
n = len(s)
word_length = len(words[0])
words_size = len(words)
window_length = word_length * len(words)
start = 0
word_cnt = {}
for word in words:
if word in word_cnt:
word_cnt[word] += 1
else:
word_cnt[word] = 1
cur_word_cnt = {}
for i in range(word_length):
cur_cnt = 0
left = i
cur_word_cnt.clear()
for j in range(i, n - word_length + 1, word_length):
word = s[j:j + word_length]
if word in word_cnt:
cur_word_cnt[word] = cur_word_cnt.get(word, 0) + 1
cur_cnt += 1
while cur_word_cnt[word] > word_cnt[word]:
left_word = s[left:left + word_length]
cur_word_cnt[left_word] -= 1
cur_cnt -= 1
left += word_length
if cur_cnt == words_size:
answer.append(left)
else:
cur_word_cnt.clear()
cur_cnt = 0
left = j + word_length
return answer