Welcome to the String Processing template collection! These are ready-to-use C++ snippets for the core string patterns: sliding window, two pointers, string matching, manipulation, and parsing. If you already know the array templates, you’re most of the way there — strings use the same ideas with character-level twists. See also Arrays & Strings for KMP and rolling hash.
String problems are array problems in disguise. Most string patterns — sliding window, two pointers, prefix computation — work identically to their array counterparts. The main difference is that you operate on characters and often track frequencies with a hash map or fixed-size array.
When to use: The problem asks for “longest substring without repeating characters”, “minimum window containing all characters”, or any contiguous substring optimization with a frequency constraint.
When to use: The problem asks to “find a pattern in text”, mentions “KMP”, or requires efficient O(n+m) substring search instead of brute-force O(n·m).
KMP Algorithm
vector<int>buildKMP(stringpattern){intm=pattern.size();vector<int>lps(m,0);intlen=0,i=1;while(i<m){if(pattern[i]==pattern[len]){lps[i++]=++len;}else{if(len!=0){len=lps[len-1];}else{lps[i++]=0;}}}returnlps;}intkmpSearch(stringtext,stringpattern){intn=text.size(),m=pattern.size();vector<int>lps=buildKMP(pattern);inti=0,j=0;while(i<n){if(text[i]==pattern[j]){i++;j++;}if(j==m){returni-j;// Found at index i - j}elseif(i<n&&text[i]!=pattern[j]){if(j!=0){j=lps[j-1];}else{i++;}}}return-1;}
ID
Title
Link
Solution
28
Find the Index of the First Occurrence in a String
When to use: The problem says “anagram”, “group anagrams”, “remove duplicates”, or requires rearranging or classifying strings by their character composition.
// Remove All Adjacent DuplicatesstringremoveDuplicates(strings){stringresult;for(charc:s){if(!result.empty()&&result.back()==c){result.pop_back();}else{result.push_back(c);}}returnresult;}// Remove All Adjacent Duplicates II (k duplicates)stringremoveDuplicates(strings,intk){vector<pair<char,int>>st;for(charc:s){if(!st.empty()&&st.back().first==c){st.back().second++;if(st.back().second==k){st.pop_back();}}else{st.push_back({c,1});}}stringresult;for(auto&[c,count]:st){result.append(count,c);}returnresult;}
When to use: The problem says “decode string”, “valid abbreviation”, “nested brackets”, or requires interpreting a string according to grammar rules.
Valid Word Abbreviation
boolvalidWordAbbreviation(stringword,stringabbr){inti=0,j=0;intn=word.size(),m=abbr.size();while(i<n&&j<m){if(isdigit(abbr[j])){if(abbr[j]=='0')returnfalse;// Leading zerointnum=0;while(j<m&&isdigit(abbr[j])){num=num*10+(abbr[j]-'0');j++;}i+=num;}else{if(word[i]!=abbr[j])returnfalse;i++;j++;}}returni==n&&j==m;}