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

For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC".

Hash Table + Two Pointer

复杂度
O(N),O(N)

思路
类似two pointer的想法。每次维护一个窗口。

代码

public String minWindow(String s, String t) {
    int start = 0, len = Integer.MAX_VALUE;
    int[] times = new int[256];
    int[] stimes = new int[256];
    for(int i = 0; i < t.length(); i ++) {
        times[t.charAt(i)] ++;
    }
    int cnt = 0;
    int begin = -1, end = 0;
    for(int i = 0; i < s.length(); i ++) {
        char ch = s.charAt(i);
        stimes[ch] ++;
        if(stimes[ch] <= times[ch]) cnt ++;
        if(cnt == t.length()) {
            while(start < s.length() && stimes[s.charAt(start)] > times[s.charAt(start)]) {
                stimes[s.charAt(start)] --;
                start ++;
            }
            //
            if(i - start + 1 < len) {
                begin = start;
                end = i;
                len = i - start + 1;
            }
            stimes[s.charAt(start)] --;
            start ++;
            cnt --;
        }
    }
    return begin == -1 ? "" : s.substring(begin, end + 1);
}

hellolittleJ17
10 声望11 粉丝