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);
}
};
本文介绍了一种高效算法来查找给定字符串中的最长回文子串。通过两种情况(奇数长度和偶数长度回文)进行讨论,并提供了一个C++实现示例。

3910

被折叠的 条评论
为什么被折叠?



