原题链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1092
思路:区间DP,如果str[i]==str[j],dp[i][j] = dp[i+1][j-1],否则 dp[i][j] = min(dp[i+1][j],dp[i][j+1])+1, O(n^2)状态,O(1)转移
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAXN = 1005;
int dp[MAXN][MAXN];
int main() {
memset(dp, 0, sizeof(dp));
char str[MAXN];
scanf("%s", str);
int len = strlen(str);
for (int l = 2; l <= len; l++) {
for (int i = 0; i + l - 1 < len; i++) {
int j = i + l - 1;
if (str[i] == str[j]) {
if (l != 2) dp[i][j] = dp[i + 1][j - 1];
else dp[i][j] = 0;
}
else {
dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1;
}
}
}
printf("%d\n", dp[0][len - 1]);
return 0;
}