- Medium
- Given a string
s
, return the longest palindromic substring ins
.
We go over the string, and test each char in the string with the following process. First, we look for the chars adjacent to the one we are looking at and see if they are the same.
For example, 'cabbad'. If we are looking at the "b", then we see from the right that the first is also "b" so we record that and add that to the palindromic string we are creating.
Then we look at both sides of the string. If the left side and the right side are the same, then we extend the string.
class Solution:
def longestPalindrome(self, s: str) -> str:
n=len(s)
currmax=0
ans=""
for i in range(n):
right=i
while right<n and s[i]==s[right]:
right+=1
left=i-1;
while left>=0 and right<n and s[left]==s[right]:
left-=1
right+=1
if right-left>currmax:
currmax=right-left
ans=s[left+1:right]
return ans