Skip to content

Commit 18947f7

Browse files
committed
solve : longest palindromic substring
1 parent a05b534 commit 18947f7

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# O(n^2)
2+
# O(1)
3+
class Solution:
4+
def longestPalindrome(self, s: str) -> str:
5+
if len(s) <= 1:
6+
return s
7+
8+
def expand_from_center(left, right):
9+
while left >= 0 and right < len(s) and s[left] == s[right]:
10+
left -= 1
11+
right += 1
12+
return s[left + 1 : right]
13+
14+
max_str = s[0]
15+
16+
for i in range(len(s) - 1):
17+
odd = expand_from_center(i, i)
18+
even = expand_from_center(i, i + 1)
19+
20+
if len(odd) > len(max_str):
21+
max_str = odd
22+
if len(even) > len(max_str):
23+
max_str = even
24+
25+
return max_str

0 commit comments

Comments
 (0)