首页 > 其他 > 详细

LeetCode最小窗口子字符串以及求解子字符串模板

时间:2017-11-18 18:14:31      阅读:268      评论:0      收藏:0      [点我收藏+]

LeetCode原题地址

题干:

给定字符串S和T,以O(n)复杂度在S中找出包含T中所有字符的最小窗口子字符串。

示例:

S = "ADOBECODEBANC"
T = "ABC"

最小窗口是"BANC".

备注:

如果没有结果,返回空字符串""。

如果有多个窗口,保证只有一个最小解。

Discuss中的答案(并且给出了一个求解所有子字符串问题的模板):

原题的解:

 1 string minWindow(string s, string t) {
 2         vector<int> map(128,0);
 3         for(auto c: t) map[c]++;
 4         int counter = t.size(), begin = 0, end = 0, d = INT_MAX, head = 0;
 5         while(end<s.size()){
 6             if(map[s[end++]]-- > 0) counter--; //in t
 7             while(counter == 0){ //valid
 8                 if(end - begin < d)  d = end - (head = begin);
 9                 if(map[s[begin++]]++ == 0) counter++;  //make it invalid
10             }  
11         }
12         return d==INT_MAX? "":s.substr(head, d);
13     }

上面的代码要理解两点:

1.自增语句,i++是i先不自加,在语句完后自加。

2.vector<int> map(128,0)可以理解为一个数组,也可以理解为对于可见的ASCII字符永远不会冲突的hashmap

接下来是模板:

对于大多数子字符串问题,给定一个字符串,需要找到一个满足某些条件的子字符串,通用的方法是使用一个hashmap和两个指针(begin和end,此指针非彼指针)。

int findSubstring(string s){
        vector<int> map(128,0);
        int counter; // check whether the substring is valid
        int begin=0, end=0; //two pointers, one point to tail and one  head
        int d; //the length of substring

        for() { /* initialize the hash map here */ }

        while(end<s.size()){

            if(map[s[end++]]-- ?){  /* modify counter here */ }

            while(/* counter condition */){ 
                 
                 /* update d here if finding minimum*/

                //increase begin to make it invalid/valid again
                
                if(map[s[begin++]]++ ?){ /*modify counter here*/ }
            }  

            /* update d here if finding maximum*/
        }
        return d;
  }

 

LeetCode最小窗口子字符串以及求解子字符串模板

原文:http://www.cnblogs.com/friedRib/p/7857387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!