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 empty string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
reference: https://www.youtube.com/watch?v=63i802XLgOM
Solution:two pointers 滑动窗 + count_Map
思路:
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
class Solution {
public String minWindow(String s, String t) {
if(s == null || t == null || s.length() == 0 || t.length() == 0) return "";
int match_count = 0;
String result = "";
int[] s_arr = new int[256];
int[] t_arr = new int[256];
for(char c: t.toCharArray()) {
t_arr[c]++;
}
int left = findNextIndex(s, 0, t_arr);
if(left == s.length()) return ""; // no char in S matches t
int right = left;
while(right < s.length()) {
int right_char = s.charAt(right);
if(s_arr[right_char] < t_arr[right_char]) {
match_count++;
}
s_arr[right_char]++;
while(left < s.length() && match_count == t.length()) {
if(result.isEmpty() || result.length() > right - left + 1) {
result = s.substring(left, right + 1);
}
int left_char = s.charAt(left);
if(s_arr[left_char] <= t_arr[left_char]) {
match_count--;
}
s_arr[left_char]--;
left = findNextIndex(s, left + 1, t_arr);
}
right = findNextIndex(s, right + 1, t_arr);
}
return result;
}
private int findNextIndex(String s, int start, int[] t_arr) {
while(start < s.length()) {
char c = s.charAt(start);
if(t_arr[c] != 0) return start;
start++;
}
return start;
}
}