动态规划实现
分析:O(n²)时间复杂度,O(n²)
以下为C#实现
public class Solution {
public string LongestPalindrome(string s) {
bool[,] table=new bool[1000,1000];
int i,len=s.Length,longestLength=1,startIndex=0;
for(i=0;i<len;i++){//长度为1的回文串
table[i,i]=true;
}
for(i=0;i<len-1;i++)//长度为2的回文串
{
if(s[i]==s[i+1])
table[i,i+1]=true;
}
for(i=0;i<s.Length-1;i++)//长度为2的回文串
{
if(s[i]==s[i+1])
{
table[i,i+1]=true;
longestLength=2;
startIndex=i;
}
}
for(i=3;i<=len;i++)//长度大于3的回文串
{
for(int j=0;j<len-i+1;j++)
{
int k=i+j-1;//j的对称位置
if(s[j]==s[k]&&table[j+1,k-1])
{
table[j,k]=true;
longestLength=i;
startIndex=j;
}
}
}
return s.Substring(startIndex,longestLength);
}
}
另一种实现
分析:从一个中心开始左右扩展一个字符串,判断是否是回文字符串,需要O(n)复杂度,总共有2n-1个中心,时间复杂度就是O(n²)。另外,空间复杂度为O(1)。
以下为C#实现
public class Solution {
public string LongestPalindrome(string s) {
int len1=0,len2=0,len=0,maxLen=0,index=0;
for(int i=0;i<s.Length;i++){
len1=ExpandAroundCenter(s,i,i);
len2=ExpandAroundCenter(s,i,i+1);
len=Math.Max(len1,len2);
if(len>maxLen)
{
maxLen=len;
index=i-(maxLen-1)/2;
}
}
return s.Substring(index,maxLen);
}
private int ExpandAroundCenter(string s,int left,int right){
while(left>=0&&right<=s.Length-1&&s[left]==s[right]){
left--;
right++;
}
return right-left-1;
}
}