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.
Input: s ="abcde", t ="ecdba"Output: 5Explanation:
Concatenating `"abc"` from `s` and `"ba"` from `t` results in`"abcba"`, which
is a palindrome of length 5.
To form the longest palindrome by concatenating a substring from s and a substring from t (possibly empty), we can try all possible splits and check for palindromes that cross the boundary. We use dynamic programming to check for palindromes efficiently.
classSolution {
public:int longestPalindrome(string s, string t) {
string u = s + t;
int n = s.size(), m = t.size(), ans =0, N = n + m;
for (int c =0; c < N; ++c) {
for (int d =0; d <2; ++d) {
int l = c, r = c + d;
while (l >=0&& r < N && u[l] == u[r]) {
if ((l < n && r >= n) || (l >= n && r < n))
ans = max(ans, r - l +1);
l--; r++;
}
}
}
return ans;
}
};
1
// Omitted for brevity. See Python for main logic.
1
// Omitted for brevity. See Python for main logic.
1
// Omitted for brevity. See Python for main logic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
deflongestPalindrome(self, s: str, t: str) -> int:
u = s + t
n, m = len(s), len(t)
ans =0 N = n + m
for c in range(N):
for d in range(2):
l, r = c, c + d
while l >=0and r < N and u[l] == u[r]:
if (l < n and r >= n) or (l >= n and r < n):
ans = max(ans, r - l +1)
l -=1 r +=1return ans
1
// Omitted for brevity. See Python for main logic.
1
// Omitted for brevity. See Python for main logic.