题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
C++实现,算法效率较高:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
int len=str.length();
int index=0;
int index1=0,index2=0;
for(int i=0;i<len;++i) //遍历一次
{
index1=0;
index2=1;
int m=i,n=i+1;
while(str[m]==str[n]&&n<len&&m>=0) //对比每个字符和其后面一个字符是否相等,相等则接着对比
{
index1+=2;
m--;
n++;
}
int a=i,b=i+2;
while(str[a]==str[b]&&b<len) //对比每一个字符前后是否相等,相等则继续对比
{
index2+=2;
a--;
b++;
}
if(index1>index) index=index1;
if(index2>index) index=index2; //判断回文串的最大长度
}
cout<<index<<endl;
}
return 0;
} 
