forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheunhwa99.java
More file actions
42 lines (34 loc) · 1.15 KB
/
eunhwa99.java
File metadata and controls
42 lines (34 loc) · 1.15 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
class Solution {
// TP: O(N+M)
// SP: O(1)
public String minWindow(String s, String t) {
int[] tFreq = new int[128];
for (char c : t.toCharArray()) {
tFreq[c]++;
}
int left = 0;
int right = 0;
int minLen = Integer.MAX_VALUE;
int minLeft = 0;
int count = 0;
int tLen = t.length();
while (right < s.length()) {
if (tFreq[s.charAt(right++)]-- > 0) { // tFreq[s.charAt(right++)]-- > 0 -> s.charAt(right) is in t
count++; // s의 문자가 t에 있기 때문에 count를 증가시킨다.
}
if (count == tLen) {
// 아래 while문은 left를 옮기면서 s의 문자가 t에 있는지 확인한다. (최소 길이를 찾기 위해)
while (left < right && tFreq[s.charAt(left)] < 0) { // tFreq[s.charAt(left)] < 0 -> s.charAt(left) is not in t
tFreq[s.charAt(left++)]++;
}
if (right - left < minLen) {
minLen = right - left;
minLeft = left;
}
tFreq[s.charAt(left++)]++; // left 한 칸 올리기
count--;
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLen);
}
}