一、Problem
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).
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.
二、Solution
方法一:滑動窗口
不算 hard 題…
- 如果窗口內部含有 t 中的所有字符,那麼可以嘗試去縮小窗口的左邊界,來求出最小的覆蓋長度。
- 否則,繼續右移窗口的右邊界,來尋找 t 中的所有字符。
class Solution {
public String minWindow(String s, String t) {
int n = s.length(), m = t.length(), mp[] = new int[258];
for (char c : t.toCharArray()) mp[c]++;
int l = 0, r = 0, match = 0, l_bound = 0, r_bound = 0, min = n+5;
while (r < n) {
char c = s.charAt(r);
if (--mp[c] >= 0) //mp記錄的是t的所有字符,如果找到了t中的字符
match++;
while (match == m) {
if (min > r - l + 1) {
min = r - l + 1;
l_bound = l;
r_bound = r + 1;
}
char ch = s.charAt(l);
if (++mp[ch] >= 1) //判斷t中的字符是否移出了窗口
match--;
l++;
}
r++;
}
return s.substring(l_bound, r_bound);
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,