File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
leetcode.com 5. Longest Palindromic Substring v3 Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def longestPalindrome (self , s : str ) -> str :
3
+ min_left , max_right = 0 , 0
4
+ max_length = 0
5
+
6
+ for i in range (len (s )):
7
+ right = left = i
8
+
9
+ while 0 <= left and right < len (s ):
10
+ if s [left ] == s [right ]:
11
+ left , right = left - 1 , right + 1
12
+ else :
13
+ break
14
+
15
+ if max_length < (right - 1 ) - (left + 1 ) + 1 :
16
+ max_length = (right - 1 ) - (left + 1 ) + 1
17
+ min_left , max_right = (left + 1 ), (right - 1 )
18
+
19
+ left = i
20
+ right = left + 1
21
+
22
+ while 0 <= left and right < len (s ):
23
+ if s [left ] == s [right ]:
24
+ left , right = left - 1 , right + 1
25
+ else :
26
+ break
27
+
28
+ if max_length < (right - 1 ) - (left + 1 ) + 1 :
29
+ max_length = (right - 1 ) - (left + 1 ) + 1
30
+ min_left , max_right = (left + 1 ), (right - 1 )
31
+
32
+ return s [min_left :max_right + 1 ]
Original file line number Diff line number Diff line change
1
+ from unittest import TestCase
2
+ from main import Solution
3
+
4
+ class TestSolution (TestCase ):
5
+ def test1_longest_palindrome (self ):
6
+ sln = Solution ()
7
+ self .assertEqual ('bab' , sln .longestPalindrome ('babad' ))
You can’t perform that action at this time.
0 commit comments