76. Minimum Window Substring

给定两个字符串S和T,求在S中的一个最小的窗口,使得T中所有字母都出现。
思路:two pointers思想,用一个指针指向出现所有字符的结尾,另一个指针指向包含所有字符的开始,然后查看开始指针能不能将窗口变短。
使用hashtable来记录T串中的内容(键为字符,值为字符出现的 次数),然后查看S串中是否一一出现,根据字符出现的次数判断,对字符是否完全出现通过计数来判断。
在leetcode中看到这类问题的一个模板:
对于大多数字符串问题,我们给定一个字符串,需要找到一个满足一些限制的子字符串。一般的方法是使用hashmap辅助两个指针。模板如下:

int findSubstring(string s){
        vector<int> map(128,0);
        int counter; // 用来检查子串是否有效
        int begin=0, end=0; //两个指针,一个指向头部,一个指向尾部
        int d; //子串的长度

        for() { /* 初始化hash map*/ }

        while(end<s.size()){

            if(map[s[end++]]-- ?){  /* 修改counter值*/ }

            while(/* 根据counter值进行判断是否满足条件 */){ 

                 /* 如果找到最小值,更新最小值*/

                //向前移动头部指针,使子串在此有效/无效

                if(map[s[begin++]]++ ?){ /*在此修改counter*/ }
            }  

            /* 如果找到更小的值,更新d*/
        }
        return d;
  }

当要求查找最大子串时,需要在内层循环之后更新最大值,以保证子字符串有效;当要求查找最小子串时,应该在内层循环内更新最小值。

/*
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

寻找最小窗口
*/


class Solution {
public:
    string minWindow(string s, string t) {
      vector<int> hashmap(129,0);
      for(int i=0;i<t.size();i++) hashmap[t[i]]++;
      int begin=0,end=0,d=INT_MAX,head=0;
      int count=t.size();
      while(end<s.size())
      {
          if(hashmap[s[end]] > 0) 
              count--;
          hashmap[s[end]]--;
          end++;
          while(count==0)
          {
              if(d > end-begin) d=end - begin,head=begin;
              if(hashmap[s[begin]]==0) count++;
              hashmap[s[begin]]++;
              begin++;
          }
      }
      return d==INT_MAX ? "" : s.substr(head,d);
    }
};

解决无重复字符的最长字符串:

int lengthOfLongestSubstring(string s) {
        vector<int> map(128,0);
        int counter=0, begin=0, end=0, d=0; 
        while(end<s.size()){
            if(map[s[end++]]++>0) counter++; 
            while(counter>0) if(map[s[begin++]]-->1) counter--;
            d=max(d, end-begin); //while valid, update d
        }
        return d;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值