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

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

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

tag: two pointers

class Solution {
    public String minWindow(String s, String t) {

        int n = s.length(), m = t.length();
        int i = 0, j = 0;
        int[] hash1 = new int[256];
        int[] hash2 = new int[256];

        for (int k = 0; k < m; k++){
            hash2[t.charAt(k)]++;
        }

        int minLen = Integer.MAX_VALUE;
        String ans = "";
        while (i < n){
            while (j < n && !cover(hash1, hash2)){
                hash1[s.charAt(j)]++;
                j++;
            }

            int len = j - i;
            if (len < minLen && cover(hash1, hash2)){
                ans = s.substring(i, j);
                minLen = len;
                //System.out.println("i: " + i + " j: " + j + " ans: " + ans);
            }

            hash1[s.charAt(i)]--;
            i++;
        }

        return ans;
    }

    private boolean cover(int[] a, int[] b){
        for (int i = 0; i < 256; i++){
            if (a[i] < b[i]){
                return false;
            }
        }

        return true;
    }
}

results for ""

    No results matching ""