LeetCode 1312. Minimum Insertion Steps to Make a String Palindrome Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1312. Minimum Insertion Steps to Make a String Palindrome

Description

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 do not 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".

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def minInsertions(self, s: str) -> int: @cache def dfs(i: int, j: int) -> int: if i >= j: return 0 if s[i] == s[j]: return dfs(i + 1, j - 1) return 1 + min(dfs(i + 1, j), dfs(i, j - 1)) return dfs(0, len(s) - 1)(code-box)

Solution 2

PythonJavaC++Go
class Solution: def minInsertions(self, s: str) -> int: n = len(s) f = [[0] * n for _ in range(n)] for i in range(n - 2, -1, -1): for j in range(i + 1, n): if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] else: f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 return f[0][-1](code-box)

Solution 3

PythonJavaC++Go
class Solution: def minInsertions(self, s: str) -> int: n = len(s) f = [[0] * n for _ in range(n)] for k in range(2, n + 1): for i in range(n - k + 1): j = i + k - 1 if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] else: f[i][j] = min(f[i + 1][j], f[i][j - 1]) + 1 return f[0][n - 1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !