-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMinimum Window Substring.java
More file actions
94 lines (78 loc) · 2.94 KB
/
Minimum Window Substring.java
File metadata and controls
94 lines (78 loc) · 2.94 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
91
92
93
/*
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).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
*/
//O(N)
public class Solution {
public String minWindow(String S, String T) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (S == null || T == null) return "";
int length1 = S.length();
int length2 = T.length();
int[] needToFind = new int[256];
for(char c : T.toCharArray()) {
needToFind[c]++;
}
int[] hasFound = new int[256];
int min = Integer.MAX_VALUE;
String minWindow = "";
int count = 0;
for (int begin = 0, end = 0; end < length1; end++) {
if (needToFind[S.charAt(end)] == 0) continue;
hasFound[S.charAt(end)]++;
if (hasFound[S.charAt(end)] <= needToFind[S.charAt(end)]) count++;
if (count == length2) {
while (needToFind[S.charAt(begin)] == 0 || hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]) {
if (hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]) hasFound[S.charAt(begin)]--;
begin++;
}
if (end - begin + 1 < min) {
min = end - begin + 1;
minWindow = S.substring(begin, end + 1);
}
}
}
return minWindow;
}
}
//too slow
public class Solution {
public String minWindow(String S, String T) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (S == null || T == null) return "";
int length1 = S.length();
int length2 = T.length();
if (length1 < length2) return "";
int min = Integer.MAX_VALUE;
String minWindow = "";
HashSet<Character> set = new HashSet<Character>();
for (char c : T.toCharArray()) {
set.add(c);
}
for (int i = 0; i + length2 <= length1; i++) {
HashSet<Character> temp = new HashSet<Character>(set);
int k = i;
while (!temp.isEmpty()) {
char c = S.charAt(k);
if (temp.contains(c)) {
temp.remove(c);
}
k++;
if (k >= length1) break;
}
if (k - i < min) {
min = k - i;
minWindow = S.substring(i, k);
}
}
return minWindow;
}
}