1771. Maximize Palindrome Length From Subsequences
Description
You are given two strings, word1
and word2
. You want to construct a string in the following manner:
- Choose some non-empty subsequence
subsequence1
fromword1
. - Choose some non-empty subsequence
subsequence2
fromword2
. - Concatenate the subsequences:
subsequence1 + subsequence2
, to make the string.
Return the length 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.
Example 1:
Input: word1 = "cacb", word2 = "cbba" Output: 5 Explanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome.
Example 2:
Input: word1 = "ab", word2 = "ab" Output: 3 Explanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome.
Example 3:
Input: word1 = "aa", word2 = "bb" Output: 0 Explanation: You cannot construct a palindrome from the described method, so return 0.
Constraints:
1 <= word1.length, word2.length <= 1000
word1
andword2
consist of lowercase English letters.
Solutions
Solution 1: Dynamic Programming
First, we concatenate strings word1
and word2
to get string \(s\). Then we can transform the problem into finding the length of the longest palindromic subsequence in string \(s\). However, when calculating the final answer, we need to ensure that at least one character in the palindrome string comes from word1
and another character comes from word2
.
We define \(f[i][j]\) as the length of the longest palindromic subsequence in the substring of string \(s\) with index range \([i, j]\).
If \(s[i] = s[j]\), then \(s[i]\) and \(s[j]\) must be in the longest palindromic subsequence, at this time \(f[i][j] = f[i + 1][j - 1] + 2\). At this point, we also need to judge whether \(s[i]\) and \(s[j]\) come from word1
and word2
. If so, we update the maximum value of the answer to \(ans=\max(ans, f[i][j])\).
If \(s[i] \neq s[j]\), then \(s[i]\) and \(s[j]\) will definitely not appear in the longest palindromic subsequence at the same time, at this time \(f[i][j] = max(f[i + 1][j], f[i][j - 1])\).
Finally, we return the answer.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n^2)\). Here, \(n\) is the length of string \(s\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|