Skip to content

Commit f5f1c9c

Browse files
author
eunhwa99
committed
minimum window substring
1 parent 8ce714b commit f5f1c9c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
3+
// TP: O(N+M)
4+
// SP: O(1)
5+
public String minWindow(String s, String t) {
6+
int[] tFreq = new int[128];
7+
for (char c : t.toCharArray()) {
8+
tFreq[c]++;
9+
}
10+
11+
int left = 0;
12+
int right = 0;
13+
int minLen = Integer.MAX_VALUE;
14+
int minLeft = 0;
15+
int count = 0;
16+
int tLen = t.length();
17+
18+
while (right < s.length()) {
19+
if (tFreq[s.charAt(right++)]-- > 0) { // tFreq[s.charAt(right++)]-- > 0 -> s.charAt(right) is in t
20+
count++; // s의 문자가 t에 있기 때문에 count를 증가시킨다.
21+
}
22+
23+
if (count == tLen) {
24+
// 아래 while문은 left를 옮기면서 s의 문자가 t에 있는지 확인한다. (최소 길이를 찾기 위해)
25+
while (left < right && tFreq[s.charAt(left)] < 0) { // tFreq[s.charAt(left)] < 0 -> s.charAt(left) is not in t
26+
tFreq[s.charAt(left++)]++;
27+
}
28+
29+
if (right - left < minLen) {
30+
minLen = right - left;
31+
minLeft = left;
32+
}
33+
tFreq[s.charAt(left++)]++; // left 한 칸 올리기
34+
count--;
35+
}
36+
37+
}
38+
39+
return minLen == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLen);
40+
41+
}
42+
}

0 commit comments

Comments
 (0)