Suppose we have a string s, we have to find the minimum number of characters needed to be inserted so that the string becomes a palindrome.
So, if the input is like s = "mad", then the output will be 2, as we can insert "am" to get "madam".
To solve this, we will follow these steps −
Define a function dp(). This will take i, j
if i >= j, then
if s[i] is same as s[j], then
return dp(i + 1, j - 1)
return minimum of dp(i + 1, j) and dp(i, j - 1) + 1
From the main method, do the following
return dp(0, size of s - 1)
Let us see the following implementation to get better understanding −
class Solution: def solve(self, s): def dp(i, j): if i >= j: return 0 if s[i] == s[j]: return dp(i + 1, j - 1) else: return min(dp(i + 1, j), dp(i, j - 1)) + 1 return dp(0, len(s) - 1) ob = Solution() s = "mad" print(ob.solve(s))
s = "mad"