LeetCode #5: Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/
The solution to this problem involves the use of a two-pointer approach where we use the center of a potential palindrome to expand outwards to both the left and right to find the longest palindrome. We consider two cases, one where the center is a single character and another where it is a pair of characters.
Here are the steps to solve this problem:
- Define a helper function
expand
that takes in a strings
, left and right indicesleft
andright
and returns the length of the longest palindrome substring that can be formed from expanding outwards fromleft
andright
. - If the given string is empty or has length less than 1, return the string itself as the longest palindromic substring.
- Initialize variables
start
andend
to 0, which will store the starting and ending indices of the longest palindromic substring found so far. - For each character in the string, expand outwards from it using the
expand
function for two cases: one where the center is a single character and another where it is a pair of characters. - Calculate the maximum length of the palindrome substring found and update
start
andend
indices accordingly. - Return the substring from
start
toend
as the longest palindromic substring found. - Done.
Here’s the code implementation of the above steps:
class Solution:
def longestPalindrome(self, s: str) -> str:
def expand(s, left, right):
l = left
r = right
while l >= 0 and r < len(s) and s[l] == s[r]:
l-=1
r+=1
return r - l - 1
if not s or len(s) < 1:
return s
start = end = 0
for i in range(len(s)):
len1 = expand(s, i, i)
len2 = expand(s, i, i+1)
max_len = max(len1, len2)
if max_len > end - start:
start = i - (max_len - 1) // 2
end = i + max_len // 2
return s[start:end+1]
Time and Space Complexity
The time complexity of this solution is O(n^2) as we need to iterate over all possible centers in the string and expand around them. The space complexity is O(1) as we are not using any additional data structure.