Longest Almost-Palindromic Substring Problem
Description
LeetCode Problem 3844.
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.
Example 1:
Input: s = "abca"
Output: 4
Explanation:
Choose the substring "abca".
- Remove "abca".
- The string becomes "aba", which is a palindrome.
- Therefore, "abca" is almost-palindromic.
Example 2:
Input: s = "abba"
Output: 4
Explanation:
Choose the substring "abba".
- Remove "abba".
- The string becomes "aba", which is a palindrome.
- Therefore, "abba" is almost-palindromic.
Example 3:
Input: s = "zzabba"
Output: 5
Explanation:
Choose the substring "zzabba".
- Remove "zabba".
- The string becomes "abba", which is a palindrome.
- Therefore, "zabba" is almost-palindromic.
Constraints:
2 <= s.length <= 2500sconsists of only lowercase English letters.
Solution
Approach: Expand Around Each Center
Every palindrome has a center, so try all 2n - 1 centers: (i, i) for odd lengths and (i, i + 1) for even lengths.
For a center (l, r), expand outward while s[l] == s[r]. When the expansion stops, one extra character must be deleted. The deleted character can be the one at l or the one at r, so continue expanding from (l - 1, r) and from (l, r + 1) as far as the characters match, and take the longer result. The length of the substring (including the deleted character) is r1 - l1 - 1 for the first case and r2 - l2 - 1 for the second. If the first expansion already reached both ends of the string, the substring cannot grow past n, so cap the value at n. The answer is the maximum over all centers.
Complexity:
- Time:
O(n^2). - Space:
O(1).
class Solution:
def almostPalindromic(self, s: str) -> int:
def f(l: int, r: int) -> int:
while l >= 0 and r < n and s[l] == s[r]:
l -= 1
r += 1
l1, r1 = l - 1, r
l2, r2 = l, r + 1
while l1 >= 0 and r1 < n and s[l1] == s[r1]:
l1 -= 1
r1 += 1
while l2 >= 0 and r2 < n and s[l2] == s[r2]:
l2 -= 1
r2 += 1
return min(n, max(r1 - l1 - 1, r2 - l2 - 1))
n = len(s)
ans = 0
for i in range(n):
a = f(i, i)
b = f(i, i + 1)
ans = max(ans, a, b)
return ans