Sliding Window && Substring Problem

76. Minimum Window Substring as example

https://leetcode.com/problems/minimum-window-substring/discuss/26808/Here-is-a-10-line-template-that-can-solve-most-'substring'-problems

class Solution {
    public String minWindow(String s, String t) {
        int[] memo = new int[128];
        for(int i = 0; i < t.length(); i++){
            memo[t.charAt(i)]++;
        }
        
        int count = t.length(), left = 0, right = 0;
        int p1=0, p2=Integer.MAX_VALUE;
        while(right<s.length()){
            // first check if the char at right is in t
            // then check if count == 0 
            // (means the window contians all characters in t)
            if(memo[s.charAt(right++)]-->0) count--;
            /* counter condition */
            while(count == 0){
                /* update result here if finding minimum*/
                if (right-left<p2-p1) {
                    //left is inclusive
                    p1=left;
                    // right is exclusive because of right++
                    p2=right;
                }
                if (memo[s.charAt(left++)]++==0) count++;
            }
            /* update d here if finding maximum*/      
        } 
        return p2==Integer.MAX_VALUE ? "" : s.substring(p1, p2);
    }
}

Last updated