ans = n - 字符串与反转字符串的最大公共子序列
1.滚动数组 当前状态由上一行的状态转化来 使用两个数组滚动求出 还可继续优化
2.笔误导致wa了大半天j没有加一
代码
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int max(int a, int b){
return a > b?a:b;
}
char s1[5001], s2[5001];
int n;
int len = 0;
int f[2][5001];
int maxx = 0;
int main(){
while(scanf("%d", &n)!=EOF){
memset(s1, 0, sizeof(s1));
memset(s2, 0, sizeof(s2));
maxx = 0;
scanf("%s", s1);
int k = 0;
for(int i = n-1; i >= 0; i--){
s2[n-1-i] = s1[i];
}
memset(f, 0, sizeof(f));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
if(s1[i-1] == s2[j-1])
f[i%2][j] = f[(i-1)%2][j-1]+1;
else
f[i%2][j] = max(f[(i-1)%2][j],f[i%2][j-1]);
}
}
cout << n-f[n%2][n] <<endl;
}
}