dp求最长回文字串

注意的就是写出的状态方程无法通过i,j的枚举顺序得到正确的解,需要通过其他的方式,与之前的不同的还有dp数组内不一定要存储数据,也可以存储状态啊

#include <iostream>

#include <stdio.h>
#include <cstring> 
using namespace std;
const int maxn=1010;
char s[maxn];
int dp[maxn][maxn];
int main(int argc, char** argv) {
gets(s);
int len=strlen(s);
int ans=1;
memset(dp,0,sizeof(dp));
for(int i=0;i<len-1;i++){
dp[i][i]=1;
if(i<len-1){
if(s[i]==s[i+1]){
dp[i][i+1]=1;
ans=2;
}
}
}
for(int l=3;l<=len;l++){
for(int i=0;i+l-1<len;i++){
int j=i+l-1;
if(s[i]==s[j]&&dp[i+1][j-1]==1){
dp[i][j]=1;
ans=l;
}
}

printf("%d\n",ans);
return 0;
}

相关文章:

  • 2022-12-23
  • 2021-12-01
  • 2022-12-23
  • 2021-05-05
  • 2021-11-06
猜你喜欢
  • 2021-09-20
  • 2022-02-06
  • 2021-10-03
  • 2021-10-07
  • 2022-02-02
  • 2022-12-23
  • 2021-05-26
相关资源
相似解决方案