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

给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。

请你返回让 s 成为回文串的 最少操作次数 。

「回文串」是正读和反读都相同的字符串。

示例 1:

输入:s = "zzazz"
输出:0
解释:字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。
示例 2:

输入:s = "mbadm"
输出:2
解释:字符串可变为 "mbdadbm" 或者 "mdbabdm" 。
示例 3:

输入:s = "leetcode"
输出:5
解释:插入 5 个字符后字符串变为 "leetcodocteel" 。
示例 4:

输入:s = "g"
输出:0
示例 5:

输入:s = "no"
输出:1
 

提示:

1 <= s.length <= 500
s 中所有字符都是小写字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-insertion-steps-to-make-a-string-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:

  计算整体需要插入几个字符使其变为回文串,需要知道其子串变为回文需要插入几个字符。

  • 如果子串的长度为1,则不需要插入字符,即dp[i][i] = 0
  • 如果子串的长度为2:
    • if s[i] == s[i+1] : dp[i][i+1] = 0
    • else : dp[i][i+1] = 1   
  • 如果子串的长度大于2的话:
    • if s[i] == s[j]: dp[i][j] = dp[i+1][j-1]
    • else dp[i][j] = min(dp[i+1][j], dp[i][j-1]) + 1  

代码:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

const int INT_MAX = 0x7fffffff;

int main() {
    string str;
    cin >> str;
    int len = str.length();
    vector<vector<int> > dp(len + 1, vector<int>(len + 1, INT_MAX));
    // 当字符长度为1时
    for (int i = 0; i < len; ++i) dp[i][i] = 0;
    // 当字符长度为2时
    for (int i = 0; i < len - 1; ++i) {
        if (str[i] == str[i + 1])
            dp[i][i + 1] = 0;
        else
            dp[i][i + 1] = 1;
    }
    // 当字符长度大于2时
    for (int l = 3; l <= len; ++l) {
        for (int i = 0, j = l - 1; j < len; ++i, ++j) {
            if (str[i] == str[j])
                dp[i][j] = dp[i + 1][j - 1];
            else
                dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1;
        }
    }
    cout << dp[0][len - 1] << endl;
    return 0;
}
永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/14668837.html