Last active
February 6, 2017 23:57
-
-
Save Indy9000/5fe3b36d92bc65640673adf0df57fe8f to your computer and use it in GitHub Desktop.
Extract longest palindrome from a string of letters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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