对于大多数子字符串问题,我们获得一个字符串和需要寻找一个符合条件的子字符串。一个通常的解法是使用hashmap来关联两个指针,接下来是模板:
int findSubstring(string s){ vector<int> map(128,0); int counter; // 检查子字符串是否符合 int begin=0, end=0; //two pointers, one point to tail and one head int d; //子字符串的长度 for() { /* 初始化hash map */ } while(end<s.size()){ if(map[s[end++]]-- ?){ /* 改变counter */ } while(/* counter condition */){ /* 如果是找最小串则在这里更新 d*/ //increase begin to make it invalid/valid again if(map[s[begin++]]++ ?){ /*改变counter */ } } /* 如果是找最大串则在这里更新 d*/ } return d; }
76. Minimum Window Substring
string minWindow(string s, string t) { vector<int> map(128,0); for(auto c: t) map[c]++;//初始化map int counter=t.size(), begin=0, end=0, d=INT_MAX, head=0; while(end<s.size()){ if(map[s[end++]]-->0) counter--; //在s中遇到匹配的字符集则map中对应数减一和counter减一 while(counter==0){ //窗口符合条件 if(end-begin<d) d=end-(head=begin);//更新最小长度d if(map[s[begin++]]++==0) counter++; //窗口左边吐出一个值,若为匹配的字符则令map对应数加一和counter加一;
//若不匹配则窗口只单纯吐出一个值
} } return d==INT_MAX? "":s.substr(head, d); }
438. Find All Anagrams in a String