LeetCode-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".

Note: 
If there is no such window in S that covers all characters in T, return the emtpy string"".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

public class Solution {
    public String minWindow(String S, String T) {
        if (S == null || S.length() < 1 || T == null || T.length() < 1) {
            return "";
        }
        int[] n = new int[128];
        for (char c : T.toCharArray()) {
            n[c]++;
        }
        int end = 0, begin = 0, d = Integer.MAX_VALUE, head = 0, cnt = T.length();
        while (end < S.length()) {
            if (n[S.charAt(end++)]-- > 0) {
                cnt--;
            }
            while (cnt == 0) {
                if (end - begin < d) {
                    d = end - (head = begin);
                }
                if (n[S.charAt(begin++)]++ == 0) {
                    cnt++;
                }
            }
        }
        return d == Integer.MAX_VALUE ? "" : S.substring(head, head + d);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/89048214