# A trick to solve most "substring" problem

I will first give the solution then show you the magic template.

The code of solving this problem is below. It might be the shortest among all solutions provided in Discuss.

``````string minWindow(string s, string t) {
vector<int> map(128,0);
for(auto c: t) map[c]++;
int counter=t.size(), begin=0, end=0, d=INT_MAX, head=0;
while(end<s.size()){
if(map[s[end++]]-->0) counter--; //in t
while(counter==0){ //valid
if(map[s[begin++]]++==0) counter++;  //make it invalid
}
}
}

``````

Here comes the template.

For most substring problem, we are given a string and need to find a substring of it which satisfy some restrictions. A general way is to use a hashmap assisted with two pointers. The template is given below.

``````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;
}

``````

One thing needs to be mentioned is that when asked to find maximum substring, we should update maximum after the inner while loop to guarantee that the substring is valid. On the other hand, when asked to find minimum substring, we should update minimum inside the inner while loop.

The code of solving Longest Substring with At Most Two Distinct Characters is below:

``````int lengthOfLongestSubstringTwoDistinct(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>2) if(map[s[begin++]]--==1) counter--;
d=max(d, end-begin);
}
return d;
}

``````

The code of solving Longest Substring Without Repeating Characters is below:

Update 01.04.2016, thanks @weiyi3 for advise.

``````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;
}

``````

I think this post deserves some upvotes! : )

### 推荐阅读更多精彩内容

• 一大早就收到了配送中心突然停电的消息，打电话问房东，房东说没收到通知，不知几点来电。这已经是第二次了，其实我心里怀...
小戴的烧烤生活阅读 508评论 0 51
• 6月中旬，悟空单车在其官方微博黯然宣布退出共享单车市场，成为全国首家失败的共享单车企业，并由此一败成名。但悟空单车...
歪道道阅读 73评论 0 0
• 随情绪发展， 热闹之中却心未在焉。 耳朵听到的成品，他人“好奇”的幌子， 疑惑，不解充斥在想知道的人心里。
柠檬_432c阅读 100评论 0 0
• 临近过年这几天，大家都开始忙起来了，年底聚餐发奖金了，发米油蔬果了，商场超市开始买年货了，家里开始打扫卫生了，连大...
我是我的光阅读 53评论 0 0
• 2017年的最后一天，我去到了深圳参加大湾区007er的年会。 年会举办地是在一个商业气息很浓的深圳弯...
Ring娇娇阅读 89评论 7 6