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.
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 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: Dynamic Programming
- Time complexity: O(n2)
- Space complexity: O(n2)
JavaScript
js
/**
* @param {string} s
* @return {number}
*/
const minInsertions = function (s) {
const n = s.length;
const dp = Array.from({ length: n }, () => new Array(n).fill(0));
for (let index = 0; index < n; index++) {
dp[index][index] = 1;
}
for (let length = 2; length <= n; length++) {
for (let start = 0; start + length - 1 < n; start++) {
const end = start + length - 1;
if (s[start] === s[end]) {
dp[start][end] = 2 + dp[start + 1][end - 1];
} else {
dp[start][end] = Math.max(dp[start + 1][end], dp[start][end - 1]);
}
}
}
return n - dp[0][n - 1];
};