Skip to content

Commit 0eefdee

Browse files
committed
solve minimum window substring
1 parent ea463a4 commit 0eefdee

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
public class sora0319 {
2+
public class Solution {
3+
public String minWindow(String s, String t) {
4+
if (s.length() < t.length()) return "";
5+
6+
Map<Character, Integer> tCounts = new HashMap<>();
7+
Map<Character, Integer> wCounts = new HashMap<>();
8+
9+
// tCounts 초기화
10+
for (char ch : t.toCharArray()) {
11+
if (tCounts.containsKey(ch)) {
12+
tCounts.put(ch, tCounts.get(ch) + 1);
13+
} else {
14+
tCounts.put(ch, 1);
15+
}
16+
}
17+
18+
int minLow = 0;
19+
int minHigh = s.length();
20+
int low = 0;
21+
boolean found = false;
22+
23+
for (int high = 0; high < s.length(); high++) {
24+
char ch = s.charAt(high);
25+
if (wCounts.containsKey(ch)) {
26+
wCounts.put(ch, wCounts.get(ch) + 1);
27+
} else {
28+
wCounts.put(ch, 1);
29+
}
30+
31+
while (isExist(wCounts, tCounts)) {
32+
if (high - low < minHigh - minLow) {
33+
minLow = low;
34+
minHigh = high;
35+
found = true;
36+
}
37+
38+
char lowChar = s.charAt(low);
39+
if (tCounts.containsKey(lowChar)) {
40+
int count = wCounts.get(lowChar);
41+
if (count == 1) {
42+
wCounts.remove(lowChar);
43+
} else {
44+
wCounts.put(lowChar, count - 1);
45+
}
46+
} else {
47+
if (wCounts.containsKey(lowChar)) {
48+
int count = wCounts.get(lowChar);
49+
if (count == 1) {
50+
wCounts.remove(lowChar);
51+
} else {
52+
wCounts.put(lowChar, count - 1);
53+
}
54+
}
55+
}
56+
57+
low++;
58+
}
59+
}
60+
61+
if (found) {
62+
return s.substring(minLow, minHigh + 1);
63+
} else {
64+
return "";
65+
}
66+
}
67+
68+
private boolean isExist(Map<Character, Integer> window, Map<Character, Integer> target) {
69+
for (Map.Entry<Character, Integer> entry : target.entrySet()) {
70+
char ch = entry.getKey();
71+
int required = entry.getValue();
72+
73+
if (!window.containsKey(ch)) {
74+
return false;
75+
}
76+
77+
int count = window.get(ch);
78+
if (count < required) {
79+
return false;
80+
}
81+
}
82+
return true;
83+
}
84+
}
85+
}
86+
87+

0 commit comments

Comments
 (0)