Skip to content

Commit 7a9c45a

Browse files
committed
add solution: minimum-window-substring
1 parent 52cb217 commit 7a9c45a

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
'''
2+
# 76. Minimum Window Substring
3+
4+
solution reference: https://www.algodale.com/problems/minimum-window-substring/
5+
6+
## μ£Όμ–΄μ§„ λ¬Έμžμ—΄ sμ—μ„œ λ¬Έμžμ—΄ t의 λͺ¨λ“  문자λ₯Ό ν¬ν•¨ν•˜λŠ” μ΅œμ†Œ μœˆλ„μš°λ₯Ό μ°Ύμ•„ λ°˜ν™˜ν•˜κΈ° πŸ”₯
7+
8+
> μŠ¬λΌμ΄λ”© μœˆλ„μš°, μ΅œμ†Œ μœˆλ„μš° μ°ΎκΈ°, λ¬Έμžμ—΄μ˜ λΉˆλ„ 좔적, t의 λͺ¨λ“  λ¬Έμžκ°€ ν˜„μž¬ μœˆλ„μš°μ— ν¬ν•¨λ˜μ–΄ μžˆλŠ”μ§€ 좔적
9+
10+
- μœˆλ„μš°μ˜ 였λ₯Έμͺ½ 끝을 ν™•μž₯ν•˜λ©΄μ„œ, ν•„μš”ν•œ λͺ¨λ“  λ¬Έμžκ°€ ν¬ν•¨λ˜μ—ˆμ„ λ•Œ, μœˆλ„μš°μ˜ 크기λ₯Ό μ΅œμ†Œν™”ν•˜κΈ°
11+
12+
## κ°’
13+
- counts: ν•„μš”ν•œ λ¬Έμžκ°€ λͺ‡ 번 λ“±μž₯ν•˜λŠ”μ§€ 좔적
14+
- n_included: μœˆλ„μš° μ•ˆμ—μ„œ t에 ν•„μš”ν•œ 문자 개수 좔적
15+
- low, high: μŠ¬λΌμ΄λ”© μœˆλ„μš°μ˜ μ–‘ 끝
16+
- min_low max_high: λ°˜ν™˜κ°’, μŠ¬λΌμ΄λ”© μœˆλ„μš°μ˜ μ–‘ 끝
17+
18+
## s 탐색
19+
- s의 였λ₯Έμͺ½ 끝을 νƒμƒ‰ν•©λ‹ˆλ‹€.
20+
- ν˜„μž¬ λ¬Έμžκ°€ t에 μ‘΄μž¬ν•œλ‹€λ©΄(counts에 ν‚€κ°€ 쑴재)
21+
- 그리고 ν•„μš”ν•œ 문자라면(값이 1 이상)
22+
- μœˆλ„μš° λ‚΄λΆ€μ˜ ν•„μš” 문자 개수λ₯Ό ν•˜λ‚˜ μ¦κ°€μ‹œν‚΅λ‹ˆλ‹€.
23+
- ν•΄λ‹Ή 문자의 λ“±μž₯ countλ₯Ό ν•˜λ‚˜ κ°μ†Œμ‹œν‚΅λ‹ˆλ‹€.
24+
25+
## μœˆλ„μš° μΆ•μ†Œν•˜κΈ°
26+
- μ•„λž˜ 문항을 ν•„μš”ν•œ 값이 μœˆλ„μš° μ•ˆμ— μ‘΄μž¬ν•˜λŠ” λ™μ•ˆ λ°˜λ³΅ν•©λ‹ˆλ‹€.
27+
1. ν˜„μž¬ κ΅¬ν•œ μœˆλ„μš°κ°€ 더 μž‘μ€ μ§€ ν™•μΈν•˜κ³ , μž‘λ‹€λ©΄ λ°˜ν™˜ν•  μœˆλ„μš°λ₯Ό μ—…λ°μ΄νŠΈ ν•©λ‹ˆλ‹€.
28+
2. s의 μ™Όμͺ½ 끝을 νƒμƒ‰ν•©λ‹ˆλ‹€.
29+
- ν˜„μž¬ λ¬Έμžκ°€ t에 μ‘΄μž¬ν•œλ‹€λ©΄(counts에 ν‚€κ°€ 쑴재)
30+
- ν•΄λ‹Ή 문자의 λ“±μž₯ countλ₯Ό ν•˜λ‚˜ μ¦κ°€μ‹œν‚΅λ‹ˆλ‹€.
31+
- 그리고 ν•„μš”ν•œ 문자라면(값이 1 이상)
32+
- μœˆλ„μš° λ‚΄λΆ€μ˜ ν•„μš” 문자 개수λ₯Ό ν•˜λ‚˜ μΆ•μ†Œμ‹œν‚΅λ‹ˆλ‹€.(반볡문의 쑰건을 λ²—μ–΄λ‚©λ‹ˆλ‹€.)
33+
3. λ‹€μŒ 탐색 μ „ μ™Όμͺ½ μœ„μΉ˜λ₯Ό ν•˜λ‚˜ μ¦κ°€μ‹œν‚΅λ‹ˆλ‹€.
34+
35+
## λ°˜ν™˜
36+
- μ΅œμ†Œ μœˆλ„μš°μ˜ μ‹œμž‘κ³Ό 끝을 low와 high + 1둜 λ°˜ν™˜ν•˜λ˜, μœ νš¨ν•œ μœˆλ„μš°κ°€ μ•„λ‹ˆλΌλ©΄ ""을 λ°˜ν™˜ν•©λ‹ˆλ‹€.
37+
'''
38+
class Solution:
39+
def minWindow(self, s: str, t: str) -> str:
40+
min_low = 0
41+
max_high = len(s)
42+
counts = Counter(t)
43+
n_included = 0
44+
45+
low = 0
46+
# s 탐색
47+
for high in range(len(s)):
48+
char_high = s[high]
49+
if char_high in counts:
50+
if counts[char_high] > 0:
51+
n_included += 1
52+
counts[char_high] -= 1
53+
54+
# μœˆλ„μš° μΆ•μ†Œν•˜κΈ°
55+
while n_included == len(t):
56+
if high - low < max_high - min_low: # 1
57+
min_low = low
58+
max_high = high
59+
60+
char_low = s[low]
61+
if char_low in counts: # 2
62+
counts[char_low] += 1
63+
if counts[char_low] > 0:
64+
n_included -= 1
65+
66+
low += 1 # 3
67+
68+
return s[min_low: max_high + 1] if max_high < len(s) else ""

0 commit comments

Comments
Β (0)