Skip to content

Commit e2e1064

Browse files
committed
feat: minimum-window-substring
1 parent 9093505 commit e2e1064

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/minimum-window-substring/">week9-5. minimum-window-substring</a>
3+
* <li>Description: return the minimum window substring of s such that every character in t (including duplicates) is included in the window </li>
4+
* <li>Topics: Hash Table, String, Sliding Window </li>
5+
* <li>Time Complexity: O(M+N), Runtime 23ms </li>
6+
* <li>Space Complexity: O(1), Memory 45.13MB </li>
7+
*/
8+
class Solution {
9+
public String minWindow(String s, String t) {
10+
if (s.length() < t.length()) return "";
11+
12+
Map<Character, Integer> tmap = new HashMap<>();
13+
for (char c : t.toCharArray()) {
14+
tmap.put(c, tmap.getOrDefault(c, 0) + 1);
15+
}
16+
17+
Map<Character, Integer> smap = new HashMap<>();
18+
int left = 0, right = 0;
19+
int tsize = tmap.size();
20+
int ssize = 0;
21+
int start = -1, end = s.length();
22+
23+
while (right < s.length()) {
24+
char c = s.charAt(right++);
25+
if (tmap.containsKey(c)) {
26+
smap.put(c, smap.getOrDefault(c, 0) + 1);
27+
if (smap.get(c).intValue() == tmap.get(c).intValue()) {
28+
ssize++;
29+
}
30+
}
31+
32+
while (ssize == tsize) {
33+
if (right - left < end - start) {
34+
start = left;
35+
end = right;
36+
}
37+
38+
char l = s.charAt(left++);
39+
if (tmap.containsKey(l)) {
40+
smap.put(l, smap.get(l) - 1);
41+
if (smap.get(l).intValue() < tmap.get(l).intValue()) {
42+
ssize--;
43+
}
44+
}
45+
}
46+
}
47+
48+
return start == -1 ? "" : s.substring(start, end);
49+
}
50+
}

0 commit comments

Comments
 (0)