Minimum Window Substring

lc 76

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

public class Solution {
    public String minWindow(String s, String t) {
        if( s == null || s.length() == 0 || t == null || t.length() == 0) return "";
        int[] thash = new int[256];
        int[] shash = new int[256];

        initHash(thash, t);
        int j = 0;
        String res = "";
        int max = Integer.MAX_VALUE;
        for (int i = 0 ; i < s.length(); i++){
            while (j < s.length() && ! isValid(shash, thash)){
                //int index = s.charAt(j) - 'a';
                shash[s.charAt(j)]++;
                j++;

            }
            if (max > j - i && isValid(shash, thash)){
                res = s.substring(i, j);
                max = j - i;
            }
            //int index2 = s.charAt(i)- 'a';
            shash [s.charAt(i)]--;
        }
        return res;
    }

    public boolean isValid(int[] shash, int[] thash){
        for (int i = 0 ; i < 256; i++){
            if (shash[i] < thash[i]) return false;
        }
        return true;
    }

    public void initHash(int[] thash, String t){
        for ( int i = 0 ; i < t.length(); i++ ){
            int index = t.charAt(i) - 'a';
            thash[t.charAt(i)]++;
            //thash[index]++;
        }
    }
}

results matching ""

    No results matching ""