Skip to content

Commit b15bc49

Browse files
committedOct 11, 2024
feat: solve DaleStudy#285 with python
1 parent d7a0504 commit b15bc49

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
 

‎minimum-window-substring/EGON.py

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
from collections import Counter
2+
from typing import List
3+
from unittest import TestCase, main
4+
5+
6+
class Solution:
7+
def minWindow(self, s: str, t: str) -> str:
8+
return self.solve_two_pointer(s, t)
9+
10+
"""
11+
Runtime: 129 ms (Beats 50.44%)
12+
Time Complexity: O(S)
13+
- 문자열 s를 enumerate로 순회하는데 O(S)
14+
- 순회 후 left를 갱신하는 while문에서 left가 0부터 n까지 단조증가하므로 총 조회는 O(S)
15+
> O(S) + O(S) ~= O(S)
16+
17+
Memory: 17.32 MB (Beats 32.52%)
18+
Space Complexity: O(S)
19+
- counter 변수의 초기 크기는 O(T)
20+
- 반복문을 조회하며 counter 갱신, 최악의 경우 s의 모든 문자가 다르고 s == t인 경우 이므로 O(S), upper bound
21+
> O(S)
22+
"""
23+
def solve_two_pointer(self, s: str, t: str) -> str:
24+
counter = Counter(t)
25+
missing = len(t)
26+
left = start = end = 0
27+
for right, char in enumerate(s, start=1):
28+
missing -= counter[char] > 0
29+
counter[char] -= 1
30+
31+
if missing == 0:
32+
while left < right and counter[s[left]] < 0:
33+
counter[s[left]] += 1
34+
left += 1
35+
36+
if not end or right - left <= end - start:
37+
start, end = left, right
38+
39+
counter[s[left]] += 1
40+
missing += 1
41+
left += 1
42+
43+
return s[start:end]
44+
45+
46+
class _LeetCodeTestCases(TestCase):
47+
def test_1(self):
48+
s = "ADOBECODEBANC"
49+
t = "ABC"
50+
output = "BANC"
51+
self.assertEqual(Solution.minWindow(Solution(), s, t), output)
52+
53+
def test_2(self):
54+
s = "a"
55+
t = "a"
56+
output = "a"
57+
self.assertEqual(Solution.minWindow(Solution(), s, t), output)
58+
59+
def test_3(self):
60+
s = "a"
61+
t = "aa"
62+
output = ""
63+
self.assertEqual(Solution.minWindow(Solution(), s, t), output)
64+
65+
66+
if __name__ == '__main__':
67+
main()

0 commit comments

Comments
 (0)
Please sign in to comment.