-
Notifications
You must be signed in to change notification settings - Fork 2
/
76.minimum-window-substring.java
65 lines (58 loc) · 2.23 KB
/
76.minimum-window-substring.java
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
/*
* @lc app=leetcode id=76 lang=java
*
* [76] Minimum Window Substring
*/
// @lc code=start
class Solution {
public String minWindow(String s, String t) {
if (s == null || s.length() == 0 || s.length() < t.length()) {
return "";
}
//count the letters in t
Map<Character, Integer> mapT = new HashMap<>();
for (char c : t.toCharArray()) {
mapT.put(c, mapT.getOrDefault(c, 0) + 1);
}
int left = 0;
int right = 0;
int valid = 0;
int startIndex = 0;
int minLen = Integer.MAX_VALUE;
Map<Character, Integer> mapS = new HashMap<>();
while (right < s.length()) {
//new character ready to in the window
char rightChar = s.charAt(right);
right++;
//if it contains the current character, it should be put in the window map
if (mapT.containsKey(rightChar)) {
mapS.put(rightChar, mapS.getOrDefault(rightChar, 0) + 1);
//check whether their number are matched
//note: we need to add intValue() because the test case is extreeeeemely large...
if (mapS.get(rightChar).intValue() == mapT.get(rightChar).intValue()) {
valid++;
}
}
//now we can consider the left bound
while (valid == mapT.size()) {
if (right - left < minLen) {
minLen = right - left;
startIndex = left;
}
//minimize the left bound
char leftChar = s.charAt(left);
left++;
if (mapT.containsKey(leftChar)) {
//we need to consider the number of valid character
//note: we need to add intValue() because the test case is extreeeeemely large...
if (mapT.get(leftChar).intValue() == mapS.get(leftChar).intValue()) {
valid--;
}
mapS.put(leftChar, mapS.get(leftChar) - 1);
}
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(startIndex, startIndex + minLen);
}
}
// @lc code=end