#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
const int maxn=5005;
int n;
string s1,s2;
int dp[2][maxn];//dp[i][j]只依赖于dp[i-1][j],dp[i][j-1]和dp[i-1][j-1]可用滚动数组节约空间,在时间上没有优势
int main(){
while(cin>>n){
memset(dp,0,sizeof(dp));
cin>>s1;
s2=s1;
reverse(s2.begin(),s2.end());//反转字符串
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(s1[i-1]==s2[j-1]){
dp[i%2][j]=dp[(i-1)%2][j-1]+1;
}
else{
dp[i%2][j]=max(dp[i%2][j-1],dp[(i-1)%2][j]);
}
}
}
cout<<n-dp[n%2][n]<<endl;
}
return 0;
}
poj1159 Palindrome 线性dp+滚动数组
猜你喜欢
转载自blog.csdn.net/skykone1/article/details/88971265
今日推荐
周排行