5. Longest Palindromic Substring
Runtime: 325ms Beats 49.99% Memory: 17.74MB Beats 84.42%
class Solution:
def longestPalindrome(self, s: str) -> str:
"""
"babad"
b,
a, bab
b, aba
a
d
algo:
if string length is one return the string
repeat for each string charachter
REMEMBER start comparing it itself, that is: left is index and right is index
while string s character at index -1 is the same as the string s character at index + 1
decreader left index
increase right index
REMEMBER start comparing it itself, that is: left is index and right is index+1
while string s character at index + 1 is the same as string s character at index index
decreader left index
increase right index
"cbbd"
c
b, bb (while index + 1 < len(s) and s(index+1) == s(index))
b,
d
"""
if len(s) <= 1:
return s
start = 0
max_length = 1
for i in range(len(s)):
# Check for odd length palindromes
left = i
right = i
while left >= 0 and right < len(s) and s[left] == s[right]:
current_length = right - left + 1
if current_length > max_length:
start = left
max_length = current_length
left -= 1
right += 1
# Check for even length palindromes
left = i
right = i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
current_length = right - left + 1
if current_length > max_length:
start = left
max_length = current_length
left -= 1
right += 1
return s[start:start + max_length]