forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsora0319.java
More file actions
87 lines (74 loc) · 2.76 KB
/
sora0319.java
File metadata and controls
87 lines (74 loc) · 2.76 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class sora0319 {
public class Solution {
public String minWindow(String s, String t) {
if (s.length() < t.length()) return "";
Map<Character, Integer> tCounts = new HashMap<>();
Map<Character, Integer> wCounts = new HashMap<>();
// tCounts 초기화
for (char ch : t.toCharArray()) {
if (tCounts.containsKey(ch)) {
tCounts.put(ch, tCounts.get(ch) + 1);
} else {
tCounts.put(ch, 1);
}
}
int minLow = 0;
int minHigh = s.length();
int low = 0;
boolean found = false;
for (int high = 0; high < s.length(); high++) {
char ch = s.charAt(high);
if (wCounts.containsKey(ch)) {
wCounts.put(ch, wCounts.get(ch) + 1);
} else {
wCounts.put(ch, 1);
}
while (isExist(wCounts, tCounts)) {
if (high - low < minHigh - minLow) {
minLow = low;
minHigh = high;
found = true;
}
char lowChar = s.charAt(low);
if (tCounts.containsKey(lowChar)) {
int count = wCounts.get(lowChar);
if (count == 1) {
wCounts.remove(lowChar);
} else {
wCounts.put(lowChar, count - 1);
}
} else {
if (wCounts.containsKey(lowChar)) {
int count = wCounts.get(lowChar);
if (count == 1) {
wCounts.remove(lowChar);
} else {
wCounts.put(lowChar, count - 1);
}
}
}
low++;
}
}
if (found) {
return s.substring(minLow, minHigh + 1);
} else {
return "";
}
}
private boolean isExist(Map<Character, Integer> window, Map<Character, Integer> target) {
for (Map.Entry<Character, Integer> entry : target.entrySet()) {
char ch = entry.getKey();
int required = entry.getValue();
if (!window.containsKey(ch)) {
return false;
}
int count = window.get(ch);
if (count < required) {
return false;
}
}
return true;
}
}
}