Skip to content

Commit 8daca7d

Browse files
authored
Update 0005-longest-palindromic-substring.py
1 parent 1d35950 commit 8daca7d

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed
Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
11
class Solution:
22
def longestPalindrome(self, s: str) -> str:
33
res = ""
4+
resLen = 0
45

56
for i in range(len(s)):
6-
for l, r in ((i,i), (i,i+1)): # odd and even lengths
7-
while l >= 0 and r < len(s) and s[l] == s[r]:
8-
if (r - l + 1) > len(res):
9-
res = s[l:r + 1]
10-
l -= 1
11-
r += 1
7+
# odd length
8+
l, r = i, i
9+
while l >= 0 and r < len(s) and s[l] == s[r]:
10+
if (r - l + 1) > resLen:
11+
res = s[l : r + 1]
12+
resLen = r - l + 1
13+
l -= 1
14+
r += 1
1215

13-
return res
16+
# even length
17+
l, r = i, i + 1
18+
while l >= 0 and r < len(s) and s[l] == s[r]:
19+
if (r - l + 1) > resLen:
20+
res = s[l : r + 1]
21+
resLen = r - l + 1
22+
l -= 1
23+
r += 1
24+
25+
return res

0 commit comments

Comments
 (0)