lc1312 让字符串成为回文串的最少插入次数

给定长为n的字符串s,每次操作可以在字符串的任意位置插入任意1个字符,如果要让s成为回文串,至少要操作多少次?
1<=n<=500

区间dp,记dp[i][j]表示让[i,j]区间成为回文串的最少操作次数,考虑s[i]与s[j]的相等关系进行转移。

class Solution {
public:
    int dp[505][505];
    int minInsertions(string s) {
        int n = s.size();
        for (int d = 1; d <= n; d++) {
            for (int i = 0; i+d-1 < n; i++) {
                int j = i+d-1;
                if (d == 1) {
                    dp[i][j] = 0;
                } else if (d == 2) {
                    dp[i][j] = s[i]==s[j] ? 0 : 1;
                } else if (s[i] == s[j]) {
                    dp[i][j] = dp[i+1][j-1];
                } else {
                    dp[i][j] = 1 + min(dp[i+1][j], dp[i][j-1]);
                }
            }
        }
        return dp[0][n-1];
    }
};
posted @ 2024-03-21 21:34  chenfy27  阅读(4)  评论(0编辑  收藏  举报