Longest Palindrome After Substring Concatenation II Problem
Description
LeetCode Problem 3504.
You are given two strings, s and t.
You can create a new string by selecting a substring from s (possibly empty) and a substring from t (possibly empty), then concatenating them in order.
Return the length of the longest palindrome that can be formed this way.
Example 1:
Input: s = "a", t = "a"
Output: 2
Explanation:
Concatenating "a" from s and "a" from t results in "aa", which is a palindrome of length 2.
Example 2:
Input: s = "abc", t = "def"
Output: 1
Explanation:
Since all characters are different, the longest palindrome is any single character, so the answer is 1.
Example 3:
Input: s = "b", t = "aaaa"
Output: 4
Explanation:
Selecting "aaaa" from t is the longest palindrome, so the answer is 4.
Example 4:
Input: s = "abcde", t = "ecdba"
Output: 5
Explanation:
Concatenating "abc" from s and "ba" from t results in "abcba", which is a palindrome of length 5.
Constraints:
1 <= s.length, t.length <= 1000sandtconsist of lowercase English letters.
Solution
Approach: Enumerate Palindrome Centers + Dynamic Programming
According to the problem description, the concatenated palindrome string can be composed entirely of string s, entirely of string t, or a combination of both strings s and t. Additionally, there may be extra palindromic substrings in either string s or t.
Therefore, we first reverse string t and preprocess arrays g1 and g2, where g1[i] represents the length of the longest palindromic substring starting at index i in string s, and g2[i] represents the length of the longest palindromic substring starting at index i in string t.
We can initialize the answer ans as the maximum value in g1 and g2.
Next, let f[i][j] be the length of the longest common suffix of the first i characters of s and the first j characters of the reversed t; these characters pair up from the outside in.
For f[i][j], if s[i - 1] equals t[j - 1], then f[i][j] = f[i - 1][j - 1] + 1. We then update the answer:
ans = max(ans, f[i][j] * 2 + (g1[i] if i < m else 0))
ans = max(ans, f[i][j] * 2 + (g2[j] if j < n else 0))
Finally, we return the answer ans.
The time complexity is O(m(m + n)), and the space complexity is O(mn), where m and n are the lengths of strings s and t, respectively.
class Solution:
def longestPalindrome(self, s: str, t: str) -> int:
def expand(s: str, g: List[int], l: int, r: int):
while l >= 0 and r < len(s) and s[l] == s[r]:
g[l] = max(g[l], r - l + 1)
l, r = l - 1, r + 1
def calc(s: str) -> List[int]:
n = len(s)
g = [0] * n
for i in range(n):
expand(s, g, i, i)
expand(s, g, i, i + 1)
return g
m, n = len(s), len(t)
t = t[::-1]
g1, g2 = calc(s), calc(t)
ans = max(*g1, *g2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i, a in enumerate(s, 1):
for j, b in enumerate(t, 1):
if a == b:
f[i][j] = f[i - 1][j - 1] + 1
ans = max(ans, f[i][j] * 2 + (0 if i >= m else g1[i]))
ans = max(ans, f[i][j] * 2 + (0 if j >= n else g2[j]))
return ans