forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdusunax.py
More file actions
68 lines (55 loc) Β· 2.79 KB
/
dusunax.py
File metadata and controls
68 lines (55 loc) Β· 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'''
# 76. Minimum Window Substring
solution reference: https://www.algodale.com/problems/minimum-window-substring/
## μ£Όμ΄μ§ λ¬Έμμ΄ sμμ λ¬Έμμ΄ tμ λͺ¨λ λ¬Έμλ₯Ό ν¬ν¨νλ μ΅μ μλμ°λ₯Ό μ°Ύμ λ°ννκΈ° π₯
> μ¬λΌμ΄λ© μλμ°, μ΅μ μλμ° μ°ΎκΈ°, λ¬Έμμ΄μ λΉλ μΆμ , tμ λͺ¨λ λ¬Έμκ° νμ¬ μλμ°μ ν¬ν¨λμ΄ μλμ§ μΆμ
- μλμ°μ μ€λ₯Έμͺ½ λμ νμ₯νλ©΄μ, νμν λͺ¨λ λ¬Έμκ° ν¬ν¨λμμ λ, μλμ°μ ν¬κΈ°λ₯Ό μ΅μννκΈ°
## κ°
- counts: νμν λ¬Έμκ° λͺ λ² λ±μ₯νλμ§ μΆμ
- n_included: μλμ° μμμ tμ νμν λ¬Έμ κ°μ μΆμ
- low, high: μ¬λΌμ΄λ© μλμ°μ μ λ
- min_low max_high: λ°νκ°, μ¬λΌμ΄λ© μλμ°μ μ λ
## s νμ
- sμ μ€λ₯Έμͺ½ λμ νμν©λλ€.
- νμ¬ λ¬Έμκ° tμ μ‘΄μ¬νλ€λ©΄(countsμ ν€κ° μ‘΄μ¬)
- κ·Έλ¦¬κ³ νμν λ¬ΈμλΌλ©΄(κ°μ΄ 1 μ΄μ)
- μλμ° λ΄λΆμ νμ λ¬Έμ κ°μλ₯Ό νλ μ¦κ°μν΅λλ€.
- ν΄λΉ λ¬Έμμ λ±μ₯ countλ₯Ό νλ κ°μμν΅λλ€.
## μλμ° μΆμνκΈ°
- μλ λ¬Ένμ νμν κ°μ΄ μλμ° μμ μ‘΄μ¬νλ λμ λ°λ³΅ν©λλ€.
1. νμ¬ κ΅¬ν μλμ°κ° λ μμ μ§ νμΈνκ³ , μλ€λ©΄ λ°νν μλμ°λ₯Ό μ
λ°μ΄νΈ ν©λλ€.
2. sμ μΌμͺ½ λμ νμν©λλ€.
- νμ¬ λ¬Έμκ° tμ μ‘΄μ¬νλ€λ©΄(countsμ ν€κ° μ‘΄μ¬)
- ν΄λΉ λ¬Έμμ λ±μ₯ countλ₯Ό νλ μ¦κ°μν΅λλ€.
- κ·Έλ¦¬κ³ νμν λ¬ΈμλΌλ©΄(κ°μ΄ 1 μ΄μ)
- μλμ° λ΄λΆμ νμ λ¬Έμ κ°μλ₯Ό νλ μΆμμν΅λλ€.(λ°λ³΅λ¬Έμ 쑰건μ λ²μ΄λ©λλ€.)
3. λ€μ νμ μ μΌμͺ½ μμΉλ₯Ό νλ μ¦κ°μν΅λλ€.
## λ°ν
- μ΅μ μλμ°μ μμκ³Ό λμ lowμ high + 1λ‘ λ°ννλ, μ ν¨ν μλμ°κ° μλλΌλ©΄ ""μ λ°νν©λλ€.
'''
class Solution:
def minWindow(self, s: str, t: str) -> str:
min_low = 0
max_high = len(s)
counts = Counter(t)
n_included = 0
low = 0
# s νμ
for high in range(len(s)):
char_high = s[high]
if char_high in counts:
if counts[char_high] > 0:
n_included += 1
counts[char_high] -= 1
# μλμ° μΆμνκΈ°
while n_included == len(t):
if high - low < max_high - min_low: # 1
min_low = low
max_high = high
char_low = s[low]
if char_low in counts: # 2
counts[char_low] += 1
if counts[char_low] > 0:
n_included -= 1
low += 1 # 3
return s[min_low: max_high + 1] if max_high < len(s) else ""