解题思路:设 s、e 两个指针,分别指向字符串 str 首、尾,然后分两种情况讨论:
- str[s] == str[e],则原问题规模缩小为求 str[s+1, e-1] 这个子串的解;
- str[s] != str[e],又分两种情况:
- 在串末尾添加 str[s],然后对 str[s+1, e] 求解;或
- 在串头部添加 str[e],然后对 str[s, e-1] 求解。
- 取这两种情况的最小解返回。
代码:
#include <cstdio>
const int MAX = 5001;
char str[MAX];
// 解空间
short dp[MAX][MAX];
inline const int &min(const int &a, const int &b) {
return a < b ? a : b;
}
int init(int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
dp[i][j] = 0;
}
}
}
int solve(int s, int e) {
// 如子串长度小于等于 1,则视为回文串,返回 0
if (e <= s) {
return 0;
}
// 如解已知,直接返回
if (dp[s][e]) {
return dp[s][e];
}
// 第一种情况
if (str[s] == str[e]) {
// 保存已知解
return dp[s][e] = solve(s + 1, e - 1);
} else {
// 第二种情况
return dp[s][e] = 1 + min(solve(s + 1, e), solve(s, e - 1));
}
}
int main() {
int N;
while (scanf("%d", &N) != EOF) {
scanf("%s", str);
init(N);
printf("%d\n", solve(0, N - 1));
}
return 0;
}