Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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