Skip to content

Commit 03d43ee

Browse files
committed
leetcode.com 5. Longest Palindromic Substring
문제 링크: https://leetcode.com/problems/longest-palindromic-substring
1 parent 4dedcf1 commit 03d43ee

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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]
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
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'))

0 commit comments

Comments
 (0)