forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTessa1217.java
More file actions
70 lines (52 loc) ยท 2.03 KB
/
Tessa1217.java
File metadata and controls
70 lines (52 loc) ยท 2.03 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
69
import java.util.HashMap;
import java.util.Map;
class Solution {
// ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋ O(1)
public String minWindow(String s, String t) {
int strLength = s.length();
int targetLength = t.length();
// ๋ชฉํ ๋ถ์์ด์ด ์ฃผ์ด์ง ๋ฌธ์์ด๋ณด๋ค ๊ธธ๋ค๋ฉด ๋ถ๋ถ ๋ฌธ์์ด๋ก ๋ณผ ์ ์์
if (targetLength > strLength) {
return "";
}
// ๋ชฉํ ๋ฌธ์์ด์ ํ์ํ ๋ฌธ์์ ๊ทธ ๊ฐ์๋ฅผ ๋ด๋ ๋งต
Map<Character, Integer> charMap = new HashMap<>();
for (char c : t.toCharArray()) {
charMap.put(c, charMap.getOrDefault(c, 0) + 1);
}
// ํฌ ํฌ์ธํฐ ์ ์ธ
int left = 0;
int right = 0;
int minWindowLength = Integer.MAX_VALUE;
int minWindowStart = 0; // ์ต์ ์๋์ฐ ์์ ์์น
int remaining = targetLength;
while (right < strLength) {
Character end = s.charAt(right);
if (charMap.containsKey(end)) {
charMap.put(end, charMap.get(end) - 1);
if (charMap.get(end) >= 0) {
remaining--;
}
}
// target ๋ฌธ์์ด์ ๋ชจ๋ ๋ฌธ์๋ฅผ ์ฐพ์๋ค๋ฉด left ํฌ์ธํฐ ์ด๋ํ๋ฉด์
// ์ต์ ์๋์ฐ ์ฐพ๊ธฐ ์์
while (remaining == 0) {
if (right - left + 1 < minWindowLength) {
minWindowLength = right - left + 1;
minWindowStart = left;
}
char startChar = s.charAt(left);
if (charMap.containsKey(startChar)) {
charMap.put(startChar, charMap.get(startChar) + 1);
if (charMap.get(startChar) > 0) {
remaining++;
}
}
left++;
}
right++;
}
return minWindowLength == Integer.MAX_VALUE ? ""
: s.substring(minWindowStart, minWindowStart + minWindowLength);
}
}