LeetCode 1312 Minimum Insertion Steps to Make a String Palindrome (dp)

177 篇文章 0 订阅
60 篇文章 0 订阅

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.

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.

题目链接:https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/

题目大意:插入最少的字符使得字符串为回文串

题目分析:这题hard。。。?其实插入最少使之变成回文和删除最少使之变成回文是一个意思,题目的核心就是求最长回文子序列(注意是子序列,不是子串),总长减去这个值就是答案,于是dp[i][j]表示区间[i,j]的最长回文子序列

s[i] == s[j] => dp[i][j] = dp[i + 1][j - 1] + 2

s[i] != s[j] => dp[i][j] = max(dp[i][j - 1], do[i + 1][j])

16ms,时间击败80.54%

class Solution {
    public int minInsertions(String s) {
        char[] str = s.toCharArray();
        int n = str.length;
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1;
        }
        for (int l = 1; l < n; l++) {
            for (int i = 0; i + l < n; i++) {
                int j = i + l;
                if (str[i] == str[j]) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = dp[i + 1][j] > dp[i][j - 1] ? dp[i + 1][j] : dp[i][j - 1];
                }
            }
        }
        return n - dp[0][n - 1];
    }
}

因为dp只可能和前三个值有关,于是可以滚动优化成一维数组,略。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值