Skip to main content

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++:

  1. #include<iostream>
  2. using namespace std;
  3. string longestPalindrome(string s)
  4. {
  5.     string str="",rstr="",lps="";
  6.     int p=0,q=0;
  7.     for(int i=0;i<s.length();i++)
  8.     {
  9.         str=str+s[i];
  10.         rstr=s[i]+rstr;
  11.         if(str==rstr)
  12.         {
  13.             if(lps.length()<str.length())
  14.             {
  15.                 lps=str;
  16.             }
  17.         }
  18.         else
  19.         {
  20.             if(p!=0&&s[p-1]==s[i])
  21.             {
  22.                 str=s[p-1]+str;
  23.                 rstr=rstr+s[p-1];
  24.                 if(lps.length()<str.length())
  25.                 {
  26.                     lps=str;
  27.                 }
  28.                 p--;
  29.             }
  30.             else
  31.             {
  32.                 i=++q;
  33.                 str.clear();
  34.                 rstr.clear();
  35.                 str=str+s[i];
  36.                 rstr=s[i]+rstr;
  37.                 p=i;
  38.             }
  39.         }
  40.     }
  41.     return lps;
  42. }
  43. int main()
  44.  {
  45. int t;
  46. cin>>t;
  47. while(t--)
  48. {
  49.     string s;
  50.     cin>>s;
  51.     cout<<longestPalindrome(s)<<endl;
  52. }
  53. return 0;
  54. }


Here is the Video: