-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0005__longest_palindromic_substring.py
More file actions
51 lines (37 loc) · 1.21 KB
/
0005__longest_palindromic_substring.py
File metadata and controls
51 lines (37 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
LeetCode: https://leetcode.com/problems/longest-palindromic-substring/
[[Blind75]]
Given a string s, return the longest palindromic substring in s.
## Example 1
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
## Example 2
Input: s = "cbbd"
Output: "bb"
## Constraints
* 1 <= s.length <= 1000
* s consist of only digits and English letters.
"""
from unittest import TestCase
class Solution(TestCase):
def test_example_1(self):
self.assertEqual("bab", self.longestPalindrome("babad"))
def longestPalindrome(self, s: str) -> str:
longest = s[0]
for i in range(len(s)):
# odd length
left, right = i - 1, i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
if right - left + 1 > len(longest):
longest = s[left:right + 1]
left -= 1
right += 1
# even length
left, right = i, i + 1
while left >= 0 and right < len(s) and s[left] == s[right]:
if right - left + 1 > len(longest):
longest = s[left:right + 1]
left -= 1
right += 1
return longest