字符统计和滑动窗口

[LeetCode 76] Minimum Window Substring

题目

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).

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.

测试案例

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

思路

  1. 先用 record 数组统计出 t 字符串中各字符的个数。
  2. 然后依次遍历 s 中的每个字符。
  3. 用 count 遍历 记录当前串 s[i,j] 中没有涵盖的字符个数。
  4. 遍历的当前字符不是有效字符时,即record[ch] <= 0时,i++。否则,移动 j,剔除冗余字符。直到剔除了第一个有效字符为止,此时更新最小长度和起始下标:min 和 index。
  5. 重复上述过程,直至遍历结束。时间复杂度为:(O(n))

代码如下

class Solution {
    public String minWindow(String s, String t) {
        int ns = s.length(), nt = t.length();
        if(ns == 0 || nt == 0){
            return "";
        }
        int index = 0, count = nt, min = ns + 1, pos;
        int[] record = new int[65536];
        //统计t中各字符的个数
        for(int i = 0; i < nt; i++){
            record[t.charAt(i)]++;
        }
        //遍历s中的所有字符,先找到一个包含t的子串
        for(int i = 0, j = 0; i < ns; i++){
            pos = s.charAt(i);
            if(record[pos]-- > 0){
                count--;
                //然后缩减左端,直到count = 1为止,记录下长度和起始下标
                while(count == 0){
                    if(++record[s.charAt(j++)] > 0){
                        count++;
                        if(i - j + 2 < min){
                            min = i - j + 2;
                            index = j - 1;
                        }
                        break;
                    }
                }
            }
        }
        //当min为s+1时,输出空串,否则输出子串s.substring(index,index + min);
        if(min == ns + 1){
            return "";
        }
        else{
            return s.substring(index, index + min);
        }
    }
}
原文地址:https://www.cnblogs.com/echie/p/9599943.html