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

题目求字符串S中包含字符串T的最小窗口。

使用滑动窗口的方式求解。代码如下:

char* minWindow(char* s, char* t) {
    int windowsCharTotal[256] = {0};
    int tCharTotal[256] = {0};
    int needCharTypes = 0;
    char* minWindowStart = s;
    int tl = 0;
    char *p = t;
    while(*p != '\0'){
        if(tCharTotal[*p] == 0){
            ++needCharTypes;
        }
        ++tCharTotal[*p];
        ++p;
    }
    tl = p - t;//t 的长度,显然最优解长度不会低于这个值
    p = s;
    int minWindowsL = 0;
    while(*s !='\0'){
        char c = *s;
        ++s;
        ++windowsCharTotal[c];
        if(windowsCharTotal[c] == tCharTotal[c]){
            --needCharTypes;
        }
        if(needCharTypes == 0){//满足需求
            while(true){//移动窗口开始的位置得到最当前优解
                char lc = *p;
                --windowsCharTotal[lc];
                if(windowsCharTotal[lc] == tCharTotal[lc] -1){//如果窗口左侧再移动下窗口就失效了。所以这是局部最优解
                    if(minWindowsL == 0 //还没有遇到过
                       || s - p < minWindowsL){
                        minWindowsL = s - p;
                        minWindowStart = p;
                        if(minWindowsL == tl){//已经是最短的了
                            minWindowStart[minWindowsL] = '\0';
                            return minWindowStart;
                        }
                    }
                    ++p;
                    ++needCharTypes;
                    break;
                }
                ++p;
            }
        }
    }
    minWindowStart[minWindowsL] = '\0';//复用s
    return minWindowStart;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值