【leetcode】76. Minimum Window Substring​​​​​​​

230 篇文章 0 订阅

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

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

题目链接:https://leetcode.com/problems/minimum-window-substring/

解法:滑动窗口

数组储存

class Solution {
public:
    string minWindow(string s, string t) {
        int lens = s.length(), lent = t.length();
        int minw = INT_MAX, minl = -1;
        if(lens<lent) return "";
        int charlist[128]={0}, tmp[128]={0};
        for(int i=0; i<lent;++i){
            charlist[int(t[i])]++;
            tmp[int(s[i])]++;
        }
        int l=0, r=lent-1;
        while(true){
            if(hasStr(tmp, charlist)){
                if(r-l+1<minw){
                    minw = r-l+1;
                    minl=l;
                }
                tmp[int(s[l])]--;
                l++;
            }else if(r+1<lens){
                r++;
                tmp[int(s[r])]++;
            }else break;
        }
        if(minl==-1)  return "";
        else return s.substr(minl, minw);
    }
    bool hasStr(int a[], int b[]){
        int len = 128;
        for(int i=0;i<len;++i){
            if(b[i]>0 && a[i]<b[i]) return false;
        }
        return true;
    }
};

优化:判断是否满足的方法

前一种方法判断是否满足,是使用了判断整个数组里要求的内容是否相等,可以优化为使用count来计数当前还有几个目标元素没有满足。

class Solution {
public:
    string minWindow(string s, string t) {
        int lens = s.length(), lent = t.length();
        int minw = INT_MAX, minl = -1;
        if(lens<lent) return "";
        int charlist[128]={0}, count=lent;
        for(int i=0; i<lent;++i){
            charlist[int(t[i])]++;    // 记录给个ascii码对应的元素需要几个
        }
        int l=0, r=0;
        while(r<lens){
            charlist[int(s[r])]--;
            if(charlist[int(s[r])]>=0){
                count--;    // >=0说明当前r取到的元素在目标之中
            }
            while(count==0){
                if(r-l+1<minw){
                    minw=r-l+1;
                    minl=l;
                }
                charlist[int(s[l])]++;
                if(charlist[int(s[l])]>0) count++;    // >0说明该ascii码对应元素有缺
                l++;
            }
            r++;
        }
        if(minl==-1) return "";
        else return s.substr(minl, minw);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值