forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimsosleepy.java
More file actions
56 lines (45 loc) ยท 2.13 KB
/
imsosleepy.java
File metadata and controls
56 lines (45 loc) ยท 2.13 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
// DP๋ผ ์๊ฐํ๊ณ ์๊ฐ์ ๋๋ฌด ๋ง์ด์จ์ GPT์๊ฒ ๋ฌผ์ด๋ณด๋ ์์ ์ ๊ทผ ์์ฒด๋ฅผ ์๋ชปํจ
// ๋ค์ ์๊ฐํด๋ด์ผํ ๋ฏ
class Solution {
public String minWindow(String s, String t) {
if (s == null || s.length() == 0 || t == null || t.length() == 0) return "";
// 1๏ธโฃ t์ ๋ฌธ์ ๊ฐ์๋ฅผ ์นด์ดํธํด์ ์ ์ฅ
Map<Character, Integer> tCount = new HashMap<>();
for (char c : t.toCharArray()) {
tCount.put(c, tCount.getOrDefault(c, 0) + 1);
}
int required = tCount.size(); // ํ์ํ ๊ณ ์ ๋ฌธ์ ๊ฐ์
// 2๏ธโฃ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ๋ณ์ ์ด๊ธฐํ
int left = 0, right = 0; // ์๋์ฐ ํฌ์ธํฐ
int formed = 0; // t์ ๋ฌธ์ ๊ฐ์๋ฅผ ๋ง์กฑํ๋ ๊ฐ์
Map<Character, Integer> windowCounts = new HashMap<>();
int minLength = Integer.MAX_VALUE;
int startIdx = 0;
// 3๏ธโฃ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ํ์ฅ
while (right < s.length()) {
char c = s.charAt(right);
windowCounts.put(c, windowCounts.getOrDefault(c, 0) + 1);
if (tCount.containsKey(c) && windowCounts.get(c).intValue() == tCount.get(c).intValue()) {
formed++;
}
// 4๏ธโฃ ๋ชจ๋ ๋ฌธ์๊ฐ ํฌํจ๋์์ ๋, ์๋์ฐ ํฌ๊ธฐ๋ฅผ ์ค์ด๋ฉด์ ์ต์ ๊ธธ์ด ์ฐพ๊ธฐ
while (left <= right && formed == required) {
char leftChar = s.charAt(left);
// ์ต์ ๊ธธ์ด ๊ฐฑ์
if (right - left + 1 < minLength) {
minLength = right - left + 1;
startIdx = left;
}
// ์๋์ฐ ํฌ๊ธฐ๋ฅผ ์ค์ด๊ธฐ ์ํด left ์ด๋
windowCounts.put(leftChar, windowCounts.get(leftChar) - 1);
if (tCount.containsKey(leftChar) && windowCounts.get(leftChar) < tCount.get(leftChar)) {
formed--;
}
left++;
}
right++;
}
// 5๏ธโฃ ๊ฒฐ๊ณผ ๋ฐํ
return (minLength == Integer.MAX_VALUE) ? "" : s.substring(startIdx, startIdx + minLength);
}
}