Maximize Palindrome Length From Subsequences Problem
Description
LeetCode Problem 1771.
You are given two strings, word1 and word2. You want to construct a string in the following manner:
- Choose some non-empty subsequence
subsequence1fromword1. - Choose some non-empty subsequence
subsequence2fromword2. - 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 <= 1000word1andword2consist of lowercase English letters.
Solution
Approach: Dynamic Programming
Glue the two words into one string s = word1 + word2. A palindromic subsequence of s that uses a letter from both halves is exactly what the problem asks for, so the task becomes a longest-palindromic-subsequence DP with one extra condition.
Let f[i][j] be the length of the longest palindromic subsequence of s[i..j], with f[i][i] = 1.
- If
s[i] == s[j], both ends can be used:f[i][j] = f[i+1][j-1] + 2. Whenilies inword1andjlies inword2, this palindrome touches both words, so it is a candidate for the answer. - Otherwise one of the ends is dropped:
f[i][j] = max(f[i+1][j], f[i][j-1]).
Only matched pairs (i, j) with i in word1 and j in word2 update the answer, so the result is 0 when no such pair exists.
Complexity: O(n2) time and O(n2) space, where n = len(word1) + len(word2).
class Solution:
def longestPalindrome(self, word1: str, word2: str) -> int:
s = word1 + word2
n = len(s)
f = [[0] * n for _ in range(n)]
for i in range(n):
f[i][i] = 1
ans = 0
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1] + 2
if i < len(word1) <= j:
ans = max(ans, f[i][j])
else:
f[i][j] = max(f[i + 1][j], f[i][j - 1])
return ans