Problem

Given a string s, return the longest

palindromic

substring

in

1
s

.

Example 1:

1
2
3
4
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.

Example 2:

1
2
3
Input: s = "cbbd"
Output: "bb"

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

Solve

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""

for i in range(len(s)):
# odd

l , r = i , i
while -1 < l and r < len(s) and s[l] == s[r]:
if r-l+1 > len(res):
res = s[l:r+1]
l-=1
r+=1
l , r = i , i+1
while -1 < l and r < len(s) and s[l] == s[r]:
if r-l+1 > len(res):
res = s[l:r+1]
l-=1
r+=1

return res