76. Minimum Window Substring

来源:互联网 发布:数据库与大数据 编辑:程序博客网 时间:2024/05/16 01:22

给定两个字符串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;    }
原创粉丝点击