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

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.


/***********************************************************************

思路:

1,用 双指针法,两个指针夹的子字符串就是 Minimum window。【在字符串或数组中扣出指定的子字符串或子数组常常用这种思想】

2,用一个map来储存字符和出现次数的关系,map<char,int>。

3,初始化map时,用T中字符出现的字符次数来初始化,如:T="aabc",则 map[a]=2,map[b]=1,map[c]=1;

4,遍历 S, S中字符x每出现一次,map[x]--;用 count 来统计T在S中还需出现的数目。初始化 count=t.size();

每出现一次T中字符 count--;当count==0时表示S出现完了T中字符。


/**********************************************************************

代码:

class Solution{
public:
    string minWindow(string s, string t){
        map<char, int> map; //(128, 0);
        for (auto c : t) map[c]++;

        int count = t.size(), begin = 0, end = 0, head = 0,d=INT_MAX;
        while (end < s.size()){
            if (map[s[end++]]-->0) count--;
            while (count == 0){
                if (d > (end - begin)){
                    d = end - begin;
                    head = begin;
                }
                if (map[s[begin++]]++ == 0) count++;   // 为什么是 map[s[begin]]++ ??因为往后移动了就还缺一个  s[begin].
            }
        }
        return d == INT_MAX ? "" : s.substr(head,d);
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值