最长回文子串也是笔试和面试环节经常出现的一个题目,基本的思想很简单,就是从头开始,以每个点为中点位置,然后向两边搜索最长的相等的串,有一个需要注意的地方就是串的长度为偶数或者奇数时的不同情况,比如abba和aba这样的不同的子串,需要同时考虑到这两种情况,做了一个简单的实现,简单测试过,code如下:
#include <iostream>
#include <assert.h>
#include <string.h>
using namespace std;
void fun(char *str,char *des)
{
assert(str != NULL );
int len = strlen(str);
int s=0,e=0;
int ts=0,te=0;
int maxn = 0;
for(int i=0;i<len;i++)
{
// t = i;
int cnt =0;
ts = i,te = i;
while(str[ts] == str[te]
&& ts >= 0
&& te < len) //
{
ts -- , te ++;
cnt ++;
} //跳出循环,要么是ts和te到了不相等的位置上,要么是越界
if((cnt*2-1) > maxn ) //奇数
{
maxn = cnt*2 - 1;
s = ts+1; //越界的问题需要处理
e = te-1;
}
cnt =0;
ts=i,te=i+1;
while(str[ts] == str[te]
&& ts >= 0
&& te < len)
{
ts--, te++;
cnt ++;
}
if((cnt *2) > maxn ) //偶数
{
maxn = cnt *2;
s = ts+1; //越界的问题需要处理
e = te-1;
}
}
int k=0;
while(s <= e)
des[ k++ ] = str[s++];
des[k] = '\0';
}
int main()
{
char str[1000];
while(cin >> str)
{
char des[500];
memset(des,0,sizeof(des));
fun(str,des);
cout << des <<endl;
}
}