Minimum Window Substring

这个题要仔细才能做对,细节相当多。

public class Solution {
    public String minWindow(String S, String T) {
        int[] needToFind = new int[256];
        int[] hasFound = new int[256];
        for (int i = 0; i < T.length(); i++)
            needToFind[T.charAt(i)]++;
        
        String x = "";
        int min = Integer.MAX_VALUE;
        int left = 0;
        int count = 0;
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (needToFind[c] == 0)
                continue;
            
            hasFound[c]++;
            if (hasFound[c] <= needToFind[c])
                count++;
            
            if (count == T.length()) {
                while (needToFind[S.charAt(left)] == 0 || hasFound[S.charAt(left)] > needToFind[S.charAt(left)]) {
                    if (hasFound[S.charAt(left)] > needToFind[S.charAt(left)])
                        hasFound[S.charAt(left)]--;
                    left++;
                }
                if (i-left+1 < min) {
                    min = i-left+1;
                    x = S.substring(left,i+1);
                }
            }
        }
        return x;
    }
}

Leave a comment