【区间 dp】B002_让字符串成为回文串的最少插入次数(LPSs 解法)

一、题目描述

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.

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

二、题解

方法一:LPS 解法

得出 LPS 的长度 dp[0][N-1] 之后,N - dp[0][N-1] 非 LPS 的构成部分,要使这一部分融入到 LPS 中,就需要插入相同的字符。

public int minInsertions(String S) {
    int N = S.length();
    char[] s = S.toCharArray();
    int[][] dp = new int[N][N];
    for (int i = 0; i < N; i++) {
        dp[i][i] = 1;
    }
    for (int l = N-1; l >= 0; l--)
    for (int r = l+1; r < N; r++) {
        if (s[l] == s[r]) {
            dp[l][r] = dp[l+1][r-1] + 2;
        } else {
            dp[l][r] = Math.max(dp[l+1][r], dp[l][r-1]);
        }
    }
    return N - dp[0][N-1];
}

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2) O(n2)
  • 空间复杂度: O ( n 2 ) O(n^2) O(n2)

你可能感兴趣的:(#,区间,dp)