您的位置:首页 > 其它

leetcode第五题—最长回文字符串

2015-07-23 17:52 302 查看

最长回文字符串(Longest Palindromic Substring )


1.中心结点法,时间复杂度为O(n^2)
回文字符串都是对称的,有两种对称方式,一是关于字符对称,比如a,aba,cabac,这种回文字符串长度都是奇数;二是关于间隔对称,比如aa,abba,cbaabc,这种回文字符串长度都是偶数,所以要分别检测这两种情况。
中心结点法,就是遍历整个字符串,分别设为中心结点,然后第二个遍历是分别对设定的中心向左右扩展,所以复杂度为o(n^2)。
比如对于字符串abba,先检测关于字符对称,设定中心为a,发现最长回文为a,再检测关于间隔对称,给定中心为ab之间间隔,发现最长回文为空。然后坐标前移,设定中心为b,发现最长回文为b,再设定中心为bb的间隔,发现最长回文为abba,为目前最长,所以最长回文设为abba,然后坐标前移,继续检测。

给定字符串和中心结点及字符串长度,返回以该结点为中心的最长回文字符串
string expandAroundCenter(string &s,int pos1,int pos2,int n)
{
int lt=pos1;
int rt=pos2;
while(lt>=0&&rt<=n-1&&s[lt]==s[rt])
{
lt--;
rt++;
}
return s.substr(lt+1,rt-lt-1);
}


给定字符串,返回最长回文字符串,通过遍历设定中心结点,调用上面的函数实现
string longestPalindrome(string &s)
{
int n=s.size();
if(n==0)
return " ";
string longest=s.substr(0,1);

for(int i=0;i<n-1;i++)
{
//center is the character,the length is must be odd
//like aba  cabac
string p1=expandAroundCenter(s,i,i,n);
if(p1.size()>longest.size())
longest=p1;

//center is the interval,the length is must be  even
//like  bb  abba  cabbac
string p2=expandAroundCenter(s,i,i+1,n);
if(p2.size()>longest.size())
longest=p2;
}

return longest;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: