Skip to content

Commit 4d642ea

Browse files
committed
solution: 0030. Substring with Concatenation of All Words
1 parent 17b435b commit 4d642ea

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

solutions/solution_0030/__init__.py

+55-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,56 @@
1+
from collections import Counter, defaultdict
2+
3+
14
class Solution:
2-
def findSubstring(self, s: str, words: list[str]) -> list[int]: ...
5+
def findSubstring(self, s: str, words: list[str]) -> list[int]:
6+
word_length = len(words[0])
7+
word_count = Counter(words)
8+
result = []
9+
10+
for i in range(word_length):
11+
left = i
12+
current_count: defaultdict[str, int] = defaultdict(int)
13+
used_word_count = 0
14+
15+
for j in range(i, len(s) - word_length + 1, word_length):
16+
word = s[j : j + word_length]
17+
18+
if word not in word_count:
19+
left = j + word_length
20+
current_count.clear()
21+
used_word_count = 0
22+
continue
23+
24+
used_word_count += 1
25+
current_count[word] += 1
26+
27+
while current_count[word] > word_count[word]:
28+
current_count[s[left : left + word_length]] -= 1
29+
left += word_length
30+
used_word_count -= 1
31+
32+
if used_word_count == len(words):
33+
result.append(left)
34+
35+
return result
36+
37+
38+
"""풀이 설명
39+
이 문제는 주어진 문자열에서 주어진 단어들이 연속해서 등장하는 인덱스를 찾는 문제입니다.
40+
대략적인 풀이 방법은 다음과 같습니다.
41+
42+
1. 주어진 단어들을 Counter로 세어둡니다.
43+
2. 단어의 길이를 구합니다.
44+
3. 단어의 길이만큼 반복문을 돌면서 시작 인덱스를 바꿔가며 단어들을 찾습니다.
45+
4. 시작 인덱스부터 단어의 길이만큼 문자열을 자릅니다.
46+
5. 자른 문자열이 주어진 단어들 중에 있는지 확인합니다.
47+
6. 자른 문자열이 주어진 단어들 중에 없다면 시작 인덱스를 다음 인덱스로 바꾸고 다시 시작합니다.
48+
7. 자른 문자열이 주어진 단어들 중에 있다면 현재 단어의 개수를 세어둡니다.
49+
8. 현재 단어의 개수가 주어진 단어들의 개수와 같다면 결과에 시작 인덱스를 추가합니다.
50+
9. 현재 단어의 개수가 주어진 단어들의 개수보다 크다면 시작 인덱스를 다음 인덱스로 바꾸고 다시 시작합니다.
51+
10. 결과를 반환합니다.
52+
53+
이 문제를 풀이한 방법은 '슬라이딩 윈도우'라는 방법을 사용했습니다.
54+
슬라이딩 윈도우는 특정 범위를 이동하면서 문제를 해결하는 방법입니다.
55+
이 문제에서는 단어의 길이만큼 인덱스를 이동하면서 단어들을 찾았습니다.
56+
"""

0 commit comments

Comments
 (0)