You are given two strings, word1 and word2. You want to construct a string in the following manner:
Choose some non-empty subsequence subsequence1 from word1.
Choose some non-empty subsequence subsequence2 from word2.
Concatenate the subsequences: subsequence1 + subsequence2, to make the string.
Return _thelength of the longest palindrome that can be constructed in the described manner. _If no palindromes can be constructed, return 0.
A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.
A palindrome is a string that reads the same forward as well as backward.
To maximize the palindrome length, we want to build a palindrome that uses at least one character from both word1 and word2. We concatenate the words and use dynamic programming to find the longest palindromic subsequence, ensuring that the palindrome includes at least one character from each word (i.e., the palindrome starts in word1 and ends in word2, or vice versa).
Use DP to compute the longest palindromic subsequence for all substrings of s.
For every pair (i, j) where i is in word1 and j is in word2 and s[i] == s[j], try to build a palindrome with s[i] and s[j] as the two ends, and the middle part is the longest palindromic subsequence between i+1 and j-1.
classSolution {
funlongestPalindrome(word1: String, word2: String): Int {
val s = word1 + word2
val n = s.length
val n1 = word1.length
val dp = Array(n) { IntArray(n) }
for (i in n-1 downTo 0) {
dp[i][i] = 1for (j in i+1 until n) {
if (s[i] == s[j]) dp[i][j] = dp[i+1][j-1] + 2else dp[i][j] = maxOf(dp[i+1][j], dp[i][j-1])
}
}
var ans = 0for (i in0 until n1) {
for (j in n1 until n) {
if (s[i] == s[j]) {
ans = maxOf(ans, dp[i][j])
}
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
deflongestPalindrome(self, word1: str, word2: str) -> int:
s = word1 + word2
n, n1 = len(s), len(word1)
dp = [[0]*n for _ in range(n)]
for i in range(n-1, -1, -1):
dp[i][i] =1for j in range(i+1, n):
if s[i] == s[j]:
dp[i][j] = dp[i+1][j-1] +2else:
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
ans =0for i in range(n1):
for j in range(n1, n):
if s[i] == s[j]:
ans = max(ans, dp[i][j])
return ans
impl Solution {
pubfnlongest_palindrome(word1: String, word2: String) -> i32 {
let s =format!("{}{}", word1, word2);
let n = s.len();
let n1 = word1.len();
let s = s.as_bytes();
letmut dp =vec![vec![0; n]; n];
for i in (0..n).rev() {
dp[i][i] =1;
for j in i+1..n {
if s[i] == s[j] {
dp[i][j] = dp[i+1][j-1] +2;
} else {
dp[i][j] = dp[i+1][j].max(dp[i][j-1]);
}
}
}
letmut ans =0;
for i in0..n1 {
for j in n1..n {
if s[i] == s[j] {
ans = ans.max(dp[i][j]);
}
}
}
ans asi32 }
}