[LeetCode] Longest Palindrome After Substring Concatenation I

3503. Longest Palindrome After Substring Concatenation I

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.

A substring is a contiguous sequence of characters within a string.

A palindrome is a string that reads the same forward and backward.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
bool ok(string s) {
int l = 0, r = s.length() - 1;
while(l < r) {
if(s[l] != s[r]) return false;
l++,r--;
}
return true;
}
public:
int longestPalindrome(string s, string t) {
int res = 0, n = s.length(), m = t.length();
for(int a = 0; a < n; a++) for(int b = a; b <= n; b++) {
for(int c = 0; c < m; c++) for(int d = c; d <= m; d++) {
if(ok(s.substr(a, b - a) + t.substr(c, d - c))) res = max(res, d - c + b - a);
}
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/30/PS/LeetCode/longest-palindrome-after-substring-concatenation-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.