Skip to content

1312. Minimum Insertion Steps to Make a String Palindrome 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
 public:
  int minInsertions(string s) {
    return s.length() - longestPalindromeSubseq(s);
  }

 private:
  // Same as 516. Longest Palindromic Subsequence
  int longestPalindromeSubseq(const string& s) {
    const int n = s.length();
    // dp[i][j] := LPS's length in s[i..j]
    vector<vector<int>> dp(n, vector<int>(n));

    for (int i = 0; i < n; ++i)
      dp[i][i] = 1;

    for (int d = 1; d < n; ++d)
      for (int i = 0; i + d < n; ++i) {
        const int j = i + d;
        if (s[i] == s[j])
          dp[i][j] = 2 + dp[i + 1][j - 1];
        else
          dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
      }

    return dp[0][n - 1];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int minInsertions(String s) {
    return s.length() - longestPalindromeSubseq(s);
  }

  // Same as 516. Longest Palindromic Subsequence
  public int longestPalindromeSubseq(String s) {
    final int n = s.length();
    // dp[i][j] := LPS's length in s[i..j]
    int[][] dp = new int[n][n];

    for (int i = 0; i < n; ++i)
      dp[i][i] = 1;

    for (int d = 1; d < n; ++d)
      for (int i = 0; i + d < n; ++i) {
        final int j = i + d;
        if (s.charAt(i) == s.charAt(j))
          dp[i][j] = 2 + dp[i + 1][j - 1];
        else
          dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
      }

    return dp[0][n - 1];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def minInsertions(self, s: str) -> int:
    return len(s) - self._longestPalindromeSubseq(s)

  # Same as 516. Longest Palindromic Subsequence
  def _longestPalindromeSubseq(self, s: str) -> int:
    n = len(s)
    # dp[i][j] := LPS's length in s[i..j]
    dp = [[0] * n for _ in range(n)]

    for i in range(n):
      dp[i][i] = 1

    for d in range(1, n):
      for i in range(n - d):
        j = i + d
        if s[i] == s[j]:
          dp[i][j] = 2 + dp[i + 1][j - 1]
        else:
          dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

    return dp[0][n - 1]