给你10000长度字符串,然你求最长回文字串,输出长度,暴力算法肯定超时
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std;
void findBMstr(string& str){
int p[str.size()+1];
memset(p, 0, sizeof(p));
int mx = 0, id = 0;
for(int i = 1; i <= str.size(); i++){
if(mx > i){
//i的对称点的右边界是否过mx界,没有就取其对称点的值,否则就取当前可取的最大值(mx-i)
p[i] = (p[2*id - i] < (mx - i) ? p[2*id - i] : (mx - i));
}else{
//意思是当前的点为止,就赋值为1
p[i] = 1;
}
while(str[i - p[i]] == str[i + p[i]]){
p[i]++;//一直向两边拓展
}
if(i + p[i] > mx){//更新id值为边界大的那个
mx = i + p[i];
id = i;
}
}
printf("\n");
int max = 0, ii;
for(int i = 1; i < str.size(); i++){
if(p[i] > max){//寻找最值,以及索引
ii = i;
max = p[i];
}
}
max--;
cout << max << endl;
}
int main()
{
string str;
cin >> str;
string str0;
str0 += "$#";
for(int i = 0; i < str.size(); i++){
str0 += str[i];
str0 += "#";
}
findBMstr(str0);
return 0;
}