Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Code:
class Solution {
public:
int Palindromic(const string &str,int i,int j)
{
int n=str.size();
int curLen=0;
while(i>=0 && j<n && str[i]==str[j])
{
--i;
++j;
}
curLen=(j-1)-(i+1)+1;
return curLen;
}
string longestPalindrome(string s)
{
int n=s.length();
int startPos=0;
int max=1;
for(int i=0;i<n;i++)
{
int oddLen=0;
int evenLen=0;
int curLen;
oddLen=Palindromic(s,i,i);
if(i+1<n)
evenLen=Palindromic(s,i,i+1);
curLen=oddLen>evenLen?oddLen:evenLen;
if(curLen>max)
{
max=curLen;
if(max &0x1)
startPos=i-max/2;
else
startPos=i-(max-1)/2;
}
}
return s.substr(startPos,max);
}
};