Suppose we have two strings, s and t. We want to make a string in the following manner −
Select some non-empty subsequence sub1 from s.
Select some non-empty subsequence sub2 from t.
Concatenate sub1 and sub2, to make the string.
We have to find the length of the longest palindrome that can be formed in the described manner. If we cannot make any palindrome, then return 0.
So, if the input is like s = "hillrace" t = "cargame", then the output will be 7 because we can take "race" from s and "car" from r, so "racecar" is the palindrome with length 7.
To solve this, we will follow these steps −
n := size of s, m := size of t
word := s + t
dp := make a 2D array of size (n+m) x (n+m) and fill with 0
for i in range (n + m - 1) to 0, decrease by 1, do
for j in range i to n + m - 1, do
if i is same as j, then
dp[i, j] := 1
otherwise when word[i] is same as word[j], then
dp[i, j] := 2 + dp[i + 1, j - 1]
otherwise,
dp[i, j] = maximum of dp[i + 1, j] and dp[i, j - 1]
ans := 0
for i in range 0 to n - 1, do
for j in range m - 1 to -1, decrease by 1, do
if s[i] is same as t[j], then
ans = maximum of ans and dp[i, n + j]
return ans
Example
Let us see the following implementation to get better understanding
def solve(s, t): n, m = len(s), len(t) word = s + t dp = [[0] * (n + m) for _ in range(n + m)] for i in range(n + m - 1, -1,-1): for j in range(i, n + m): if i == j: dp[i][j] = 1 elif word[i] == word[j]: dp[i][j] = 2 + dp[i + 1][j - 1] else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) ans = 0 for i in range(n): for j in range(m - 1, -1, -1): if s[i] == t[j]: ans = max(ans, dp[i][n + j]) return ans s = "hillrace" t = "cargame" print(solve(s, t))
Input
[[2,2],[1,2],[3,2]], [[3,1],[3,3],[5,2]]
Output
7