Suppose we have a string s, we have to check whether we can make this string a palindrome after deleting at most k characters or not.
So, if the input is like s = "lieuvrel", k = 4, then the output will be True, we can delete three characters to get palindrome "level".
To solve this, we will follow these steps −
- Define a function lcs() . This will take a, b
- m := size of a, n := size of b
- table := matrix of size (m + 1) x (n + 1) and fill with 0
- for i in range 1 to m, do
- for j in range 1 to n, do
- if a[i - 1] is same as b[j - 1], then
- table[i, j] := 1 + table[i - 1, j - 1]
- otherwise,
- table[i, j] := maximum of table[i, j - 1] and table[i - 1, j]
- if a[i - 1] is same as b[j - 1], then
- for j in range 1 to n, do
- return table[m, n]
- From the main method do the following:
- return true when (size of s - lcs(s, reverse of s) <= k) otherwise false
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s, k): def lcs(a, b): m, n = len(a), len(b) table = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if a[i - 1] == b[j - 1]: table[i][j] = 1 + table[i - 1][j - 1] else: table[i][j] = max(table[i][j - 1], table[i - 1][j]) return table[m][n] return len(s) - lcs(s, s[::-1]) <= k ob = Solution() s = "lieuvrel" k = 4 print(ob.solve(s, k))
Input
"lieuvrel", 4
Output
True