Skip to content

Instantly share code, notes, and snippets.

@aaani
Created November 12, 2013 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaani/7433191 to your computer and use it in GitHub Desktop.
Save aaani/7433191 to your computer and use it in GitHub Desktop.
pair<pair<char,char>,int> maxLenSubstring2Chars(string s){
pair<char,int> lastChar;
lastChar.first=s[0];
lastChar.second=1;
pair<pair<char,char>,int> longestPairYet;
longestPairYet.second=-1;
pair<pair<char,char>,int> currentPair;
currentPair.first.first=s[0];
currentPair.second=-1;
for(int i=1;i<=s.length();i++){
//Check if current char present in the current pair
if(s[i]==currentPair.first.first || s[i]==currentPair.first.second) {
if(currentPair.second!=-1) currentPair.second++;
}else{ //Current char is outside current pair chars
//Before resetting current pair, check if it deserves to be stored in longest pair
if(currentPair.second>longestPairYet.second) longestPairYet=currentPair;
//Reset current pair
currentPair.first.first=s[i-1];
currentPair.first.second=s[i];
currentPair.second=lastChar.second+1;
}
//Maintain last character
if(s[i]==lastChar.first) lastChar.second++;
else{
lastChar.first=s[i];
lastChar.second=1;
}
}
return longestPairYet;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment