[LeetCode] Longest Almost-Palindromic Substring

3844. Longest Almost-Palindromic Substring

You are given a string s consisting of lowercase English letters.

A substring is almost-palindromic if it becomes a palindrome after removing exactly one character from it.

Return an integer denoting the length of the longest almost-palindromic substring in s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

class Solution {
int check1(string& s, int l, int r) {
int n = s.length();
while(0 <= l and r < n and s[l] == s[r]) {
l--, r++;
}
if(l == -1 or r == n) {
return min(n, r - l);
}
return max(check2(s,l,r+1), check2(s,l-1,r));
}
int check2(string& s, int l, int r) {
int n = s.length();
while(0 <= l and r < n and s[l] == s[r]) {
l--,r++;
}
return r - l - 1;
}
public:
int almostPalindromic(string s) {
int res = 0, n = s.length();
if(n == 2) return 2;
for(int i = 0; i < n; i++) {
res = max(res, check1(s,i,i));
if(i + 1 < n) {
res = max(res, check1(s,i,i+1));
}
if(i + 2 < n ) {
res = max(res, check2(s, i, i + 2));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/longest-almost-palindromic-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.