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 = "zzazz" Output: 0 Explanation: The string "zzazz" is already palindrome we do not need any insertions.
Input: s = "mbadm" Output: 2 Explanation: String can be "mbdadbm" or "mdbabdm".
Input: s = "leetcode" Output: 5 Explanation: Inserting 5 characters the string becomes "leetcodocteel".
1 <= s.length <= 500
s
consists of lowercase English letters.
from functools import cache
class Solution:
def minInsertions(self, s: str) -> int:
@cache
def minInsertionsSub(i: int, j: int) -> int:
if i >= j:
return 0
ret = 1 + minInsertionsSub(i + 1, j)
ret = min(ret, 1 + minInsertionsSub(i, j - 1))
if s[i] == s[j]:
ret = min(ret, minInsertionsSub(i + 1, j - 1))
return ret
return minInsertionsSub(0, len(s) - 1)