Skip to main content

Posts

Showing posts with the label Longest Palindrome in a String

Longest Palindrome in a String

Task: Find the longest palindromic sub string in given string.  Example: Input: 1 aabba Output: abba Here is the Code: Program in C++: #include<iostream> using namespace std; string longestPalindrome(string s) {     string str="",rstr="",lps="";     int p=0,q=0;     for(int i=0;i<s.length();i++)     {         str=str+s[i];         rstr=s[i]+rstr;         if(str==rstr)         {             if(lps.length()<str.length())             {                 lps=str;             }         }         else         {             if(p!=0&&s[p-1]==s[i])             {                 str=s[p-1]+str;                 rstr=rstr+s[p-1];                 if(lps.length()<str.length())                 {                     lps=str;                 }                 p--;             }             else             {                 i=++q;                 str.clear();                 rstr.clear();                 str=str+s[i];                 rstr=s[i]+rstr;