题目在此指针
解题思路:设 s、e 两个指针,分别指向字符串 str 首、尾,而后分两种状况讨论:code
代码:字符串
#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; }