Skip to content

Commit 89d849b

Browse files
Create longest-palindromic-substring.py
1 parent c3f6c97 commit 89d849b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

longest-palindromic-substring.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
class Solution:
3+
def longestPalindrome(self, s):
4+
if not s or len(s) == 1: return s
5+
min_start, max_len = 0, 1
6+
7+
i = 0
8+
while i < len(s):
9+
if len(s) - i <= max_len / 2: break
10+
j, k = i, i
11+
while k < len(s) - 1 and s[k + 1] == s[k]:
12+
k += 1
13+
14+
i = k + 1
15+
16+
while k < len(s) - 1 and j > 0 and s[k + 1] == s[j - 1]:
17+
k += 1
18+
j -= 1
19+
20+
new_len = k - j + 1
21+
if new_len > max_len:
22+
min_start = j
23+
max_len = new_len
24+
25+
return s[min_start:min_start+max_len]
26+

0 commit comments

Comments
 (0)