POJ 1159: Palindrome

题目在此指针

解题思路:设 s、e 两个指针,分别指向字符串 str 首、尾,而后分两种状况讨论:code

  1. str[s] == str[e],则原问题规模缩小为求 str[s+1, e-1] 这个子串的解;
  2. 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;
}
相关文章
相关标签/搜索