-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimum Window Substring
More file actions
90 lines (56 loc) · 1.68 KB
/
Copy pathMinimum Window Substring
File metadata and controls
90 lines (56 loc) · 1.68 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
86
87
88
89
90
LEETCODE PROBLEM SOLVING
PROBLEM->MINUMUM WINDOW SUBSTRING
import java.util.*;
class Solution {
public String minWindow(String s, String t) {
if (s.length() < t.length()) {
return "";
}
Map<Character,Integer> need = new HashMap<>();
for(char c : t.toCharArray()) {
need.put(
c,
need.getOrDefault(c,0)+1
);
}
Map<Character,Integer> window =
new HashMap<>();
int left = 0;
int formed = 0;
int required = need.size();
int minLen = Integer.MAX_VALUE;
int start = 0;
for(int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
window.put(
c,
window.getOrDefault(c,0)+1
);
if(need.containsKey(c) &&
window.get(c).intValue()
== need.get(c).intValue()) {
formed++;
}
while(formed == required) {
if(right-left+1 < minLen) {
minLen = right-left+1;
start = left;
}
char leftChar = s.charAt(left);
window.put(
leftChar,
window.get(leftChar)-1
);
if(need.containsKey(leftChar) &&
window.get(leftChar)
< need.get(leftChar)) {
formed--;
}
left++;
}
}
return minLen == Integer.MAX_VALUE
? ""
: s.substring(start,start+minLen);
}
}