-
Notifications
You must be signed in to change notification settings - Fork 2
/
76.minimum-window-substring.java
81 lines (74 loc) · 2.02 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* @lc app=leetcode id=76 lang=java
*
* [76] Minimum Window Substring
*
* https://leetcode.com/problems/minimum-window-substring/description/
*
* algorithms
* Hard (34.75%)
* Likes: 5026
* Dislikes: 342
* Total Accepted: 428.9K
* Total Submissions: 1.2M
* Testcase Example: '"ADOBECODEBANC"\n"ABC"'
*
* Given a string S and a string T, find the minimum window in S which will
* contain all the characters in T in complexity O(n).
*
* Example:
*
*
* Input: S = "ADOBECODEBANC", T = "ABC"
* Output: "BANC"
*
*
* Note:
*
*
* If there is no such window in S that covers all characters in T, return the
* empty string "".
* If there is such window, you are guaranteed that there will always be only
* one unique minimum window in S.
*
*
*/
// @lc code=start
class Solution {
public String minWindow(String s, String t) {
if(t.length()> s.length()) return "";
Map<Character, Integer> map = new HashMap<>();
for(char c : t.toCharArray()){
map.put(c, map.getOrDefault(c,0) + 1);
}
int counter = map.size();
int begin = 0, end = 0;
int head = 0;
int len = Integer.MAX_VALUE;
while(end < s.length()){
char c = s.charAt(end);
if( map.containsKey(c) ){
map.put(c, map.get(c)-1);
if(map.get(c) == 0) counter--;
}
end++;
while(counter == 0){
char tempc = s.charAt(begin);
if(map.containsKey(tempc)){
map.put(tempc, map.get(tempc) + 1);
if(map.get(tempc) > 0){
counter++;
}
}
if(end-begin < len){
len = end - begin;
head = begin;
}
begin++;
}
}
if(len == Integer.MAX_VALUE) return "";
return s.substring(head, head+len);
}
}
// @lc code=end