最长回文子串(练习...)
代码:
//最长回文串
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
int main() {
int t;scanf("%d",&t);
while(t--) {
string s;cin>>s;
string str=s;reverse(s.begin(),s.end());
int len=s.length(),dp[len+1][len+1],longlen=0,r;
memset(dp,0,sizeof(dp));
for(int i=0;i<=len;i++) {
for(int j=0;j<=len;j++) {
if(i==0||j==0) {
dp[i][j]=0;
} else if(str[i-1]==s[j-1]) {
dp[i][j]=dp[i-1][j-1]+1;
if(dp[i][j]>longlen) {
longlen=dp[i][j];r=i-1;
}
} else {
dp[i][j]=0;
}
}
}
str=str.substr(r-longlen+1,longlen);
cout<<str<<endl;
}
return 0;
}

浙公网安备 33010602011771号