Leetcode 76 Minimum Window Substring

Leetcode 76 Minimum Window Substring

Approach 1: Sliding Window

Algorithm:

  1. We start with two pointers, left and right initially pointing to the first element of the string S. 双指针,left 和 right。

  2. We use the rightright pointer to expand the window until we get a desirable window i.e. a window that contains all of the characters of T. 移动right指针, 直到包含所有T的字符。

  3. Once we have a window with all the characters, we can move the left pointer ahead one by one. If the window is still a desirable one we keep on updating the minimum window size. 当window有所有的字符之后,移动left指针,如果window仍然包含所有字符,继续移动left。

  4. If the window is not desirable any more, we repeat step 2. 移动做指针之后不包含所有字符,则移动right。

class Solution {
    public String minWindow(String s, String t) {
        char[] ss = s.toCharArray();
        char[] tt = t.toCharArray();
        
        if (tt.length == 0) {
            return "";
        }
        
        int T = 0;
        
        int[] cntT = new int[256];
        int[] cntS = new int[256];
        
        for(char c: tt){
            ++cntT[c];
            if(cntT[c] == 1){
                ++T;
            } 
        }
        
        int ansl =-1;
        int ansr = -1;
        
        int l=0;
        int r=0;
        
        int now = 0;
        
        for(l=0; l<s.length(); ++l){
            
            while(r<s.length() && now<T){
                ++cntS[ss[r]];
                // ss[r] may be repeat in String t.
                if(cntS[ss[r]] == cntT[ss[r]]){
                    ++now;
                }
                ++r;
            }
            
            if (now == T) {
                if (ansl == -1 || r - l < ansr - ansl) {
                    ansl = l;
                    ansr = r;
                }
            }
            
            -- cntS[ss[l]];
            //ss[r] may be repeat in String t.
            if(cntS[ss[l]] ==cntT[ss[l]] - 1){
                --now;
            }
        }
        
       if (ansl == -1) {
       // r > s.length && now <T
            return "";
        }else{
            return s.substring(ansl, ansr);
        }
    }
}

For example:

Input: S = “ADOBECODEBANC”, T = “ABC”
Output: “BANC”

  • left = 0 right = 5
  • left =1 right = 10
  • left = 2 right = 10
  • left =3 right =10
  • left = 4 right =10
  • left = 9 right = 12

Input: S = “ABBBBAABBANC”, T = “AAC”
Output: “ABBANC”
cntT[‘A’] = 2 cntT[‘C’] =1 and T=2
we need find a windows which satisfy cntS[‘A’] = 2 cntS[‘C’] =1 and now=2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值