**Minimum Window Substring & String类问题模板

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

Note:
If there is no such window in S that covers all characters in T, return the empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

 

牛逼的讨论:无法理解的大牛思路

https://leetcode.com/discuss/72701/here-10-line-template-that-can-solve-most-substring-problems

另一个讲解:正常人可以懂的思路

http://www.cnblogs.com/TenosDoIt/p/3461301.html

public class Solution {
public String minWindow(String S, String T) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int lens = S.length(), lent = T.length();
        int[] srcCnt = new int[256] ;//T中每个字母的个数
        int[] foundCnt = new int[256] ;//当前找到T中每个字母的个数
        char[] SS = S.toCharArray();
        char[] TT = T.toCharArray();
        for(int i = 0; i < lent; i++)
            srcCnt[TT[i]]++;
        int hasFound = 0;//已经找到的字母数目
        int winStart = -1, winEnd = lens;//窗口的左右边界
        //两个指针start和i一起扫描
        for(int i = 0, start = 0; i < lens; i++)
            if(srcCnt[SS[i]] != 0)
            {
                foundCnt[SS[i]]++;
                if(foundCnt[SS[i]] <= srcCnt[SS[i]])hasFound++;
                if(hasFound == lent)
                {//找到了一个满足的窗口
                    while(srcCnt[SS[start]] == 0 ||
                          foundCnt[SS[start]] > srcCnt[SS[start]])
                          //当S[start]不在T中,或者找到的S[start]个数大于T中S[start]个数,缩减窗口
                    {
                        if(srcCnt[SS[start]] != 0)
                            foundCnt[SS[start]]--;
                        start++;
                    }
                    if(winEnd - winStart > i - start)
                    {
                        winStart = start;
                        winEnd = i;
                    }
                    foundCnt[SS[start]]--;
                    start++;
                    hasFound--;
                }
            }
        return winStart != -1 ? S.substring(winStart, winEnd+1) : "";
    }
}

 

 

转载于:https://www.cnblogs.com/hygeia/p/5133265.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值