【LeetCode 1312】 Minimum Insertion Steps to Make a String Palindrome

题目描述

Given a string s. In one step you can insert any character at any index of the string.

Return the minimum number of steps to make s palindrome.

A Palindrome String is one that reads the same backward as well as forward.

Example 1:

Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we don't need any insertions.

Example 2:

Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".

Example 3:

Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".

Example 4:

Input: s = "g"
Output: 0

Example 5:

Input: s = "no"
Output: 1

Constraints:

1 <= s.length <= 500
All characters of s are lower case English letters.

思路

可以往左边插入或者右边插入,回文串特点是 dp[i][j]是回文串,那么dp[i+1][j-1]是回文串。子问题即 dp[i+1][j-1]需要的最少插入字符个数。遍历长度,填充dp。

代码

class Solution {
public:
    int minInsertions(string s) {
        int n = s.length();
        vector<vector<int> > dp(n, vector<int>(n, 0));
        for (int l=2; l<=n; ++l) {
            for (int i=0, j=i+l-1; j<n; ++i, ++j) {
                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;
            }
        }
        return dp[0][n-1];
    }
};

怎么感觉自己做过的dp也都忘了。。。。
新遇见的dp也基本做不出来。。。。

发布了243 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104351840