Very easy CPP code with detail explanation


#1

/* First take each character as center of a palin, it gives only string of odd length

  • Take two consecutive char as center of a palin, it gives only string of even length
  • Take string which has max length among all palin strings
    */

// Function to check palin
string ex(string &s, int p1, int p2)
{
while(p1>=0 && p2<s.length())
{
if(s[p1]==s[p2])
{
p1–; p2++;
}
else break;
}
p1++;// as it was out of palin index
p2–;// as it was out of palin index
string str;
while(p1<=p2)
str.push_back(s[p1++]);
return str;
}

string Solution::longestPalindrome(string A) {
string ans="";
int n=A.length();

// odd size palin string has center 1 char
for(int i=0; i<n; i++)
{
    string str = ex(A,i,i);
    if(ans.size() < str.size()) 
      ans=str;
}

// even size palin string has center 2 chars 
for(int i=1; i<n; i++)
{
    string str = ex(A,i-1,i);
    if(ans.size()<str.size())
    ans=str;
}
return ans;

}