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, we can try all possible splits and check for palindromes centered at the junction. The palindrome can be centered at the end of s and start of t, or fully within one string.
classSolution {
public:int longestPalindrome(string s, string t) {
int n = s.size(), m = t.size(), ans =0;
string u = s + t;
auto is_pal = [&](int l, int r) {
while (l < r) if (u[l++] != u[r--]) return false;
return true;
};
// Palindrome crossing the boundary
for (int i =0; i <= n; ++i) {
for (int j =0; j <= m; ++j) {
int l = i-1, r = n+j;
while (l >=0&& r < n+m && u[l] == u[r]) {
l--; r++;
}
ans = max(ans, r-l-1);
}
}
// Palindrome within s or t
for (int i =0; i < n+m; ++i) {
int l = i, r = i;
while (l >=0&& r < n+m && u[l] == u[r]) {
if ((l < n && r >= n) || (l >= n && r < n)) ans = max(ans, r-l+1);
l--; r++;
}
l = i; r = i+1;
while (l >=0&& r < n+m && 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.
classSolution:
deflongestPalindrome(self, s: str, t: str) -> int:
n, m = len(s), len(t)
u = s + t
ans =0# Palindrome crossing the boundaryfor i in range(n+1):
for j in range(m+1):
l, r = i-1, n+j
while l >=0and r < n+m and u[l] == u[r]:
l -=1 r +=1 ans = max(ans, r-l-1)
# Palindrome within s or tfor i in range(n+m):
l = r = i
while l >=0and r < n+m 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 +=1 l, r = i, i+1while l >=0and r < n+m 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.