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 longestpalindrome 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.
The longest palindrome inside \(s\) or \(t\) alone can be found by expanding around centers, but a concatenation may take a piece from each string and then grow a palindromic core on one side.
After reversing \(t\), a common prefix of \(s\) and the reversed \(t\) is a symmetric pair from the two originals. \(f[i][j]\) stores that matched length; appending the longest palindrome starting at \(i\) in \(s\) or at \(j\) in the reversed \(t\) covers both “one side only” and “match then extend”.
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 \(\textit{g1}\) and \(\textit{g2}\), where \(\textit{g1}[i]\) represents the length of the longest palindromic substring starting at index \(i\) in string \(s\), and \(\textit{g2}[i]\) represents the length of the longest palindromic substring starting at index \(i\) in string \(t\).
We can initialize the answer \(\textit{ans}\) as the maximum value in \(\textit{g1}\) and \(\textit{g2}\).
Next, we define \(\textit{f}[i][j]\) as the length of the palindromic substring ending at the \(i\)-th character of string \(s\) and the \(j\)-th character of string \(t\).
For \(\textit{f}[i][j]\), if \(s[i - 1]\) equals \(t[j - 1]\), then \(\textit{f}[i][j] = \textit{f}[i - 1][j - 1] + 1\). We then update the answer:
\[ \textit{ans} = \max(\textit{ans}, \textit{f}[i][j] \times 2 + (0 \text{ if } i \geq m \text{ else } \textit{g1}[i])) \\ \textit{ans} = \max(\textit{ans}, \textit{f}[i][j] \times 2 + (0 \text{ if } j \geq n \text{ else } \textit{g2}[j])) \]
Finally, we return the answer \(\textit{ans}\).
The time complexity is \(O(m \times (m + n))\), and the space complexity is \(O(m \times n)\), where \(m\) and \(n\) are the lengths of strings \(s\) and \(t\), respectively.