Skip to content

Instantly share code, notes, and snippets.

@Indy9000
Last active February 6, 2017 23:57
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 Indy9000/5fe3b36d92bc65640673adf0df57fe8f to your computer and use it in GitHub Desktop.
Save Indy9000/5fe3b36d92bc65640673adf0df57fe8f to your computer and use it in GitHub Desktop.
Extract longest palindrome from a string of letters
#include <iostream>
#include <string>
std::string longest_palindrome(const std::string& word){
if(word.size()<3)
return std::string();
std::string longest("");
for(std::size_t i=1;i<word.size()-1;++i){
auto left = i - 1;
auto right= i + 1;
if(word[left] == word[right]){
while(left >= 0 && right < word.size()){
if(word[left] != word[right]){//reached end of palindrome
break;
}
left--;right++;
}
//extract palindrome
auto p = word.substr(left+1,(right-1)-(left+1)+1);
if(longest.size()< p.size()){
longest = p;
}
}
}
return longest;
}
int main() {
std::cout << longest_palindrome("") << std::endl;
std::cout << longest_palindrome("aa") << std::endl;
std::cout << longest_palindrome("aaa") << std::endl;
std::cout << longest_palindrome("ama") << std::endl;
std::cout << longest_palindrome("madam") << std::endl;
std::cout << longest_palindrome("zzzmadam") << std::endl;
std::cout << longest_palindrome("madamzzz") << std::endl;
std::cout << longest_palindrome("aibohphobia") << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment