【字符串】A046_LC_最小覆蓋子串(滑動窗口)

一、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);
    }
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章