Skip to content

Commit faa0494

Browse files
Merge pull request #8 from codewithme-py/feat/longest-palindromic-substring-0005
problem solution & test 0005
2 parents ecc6fba + 44ce13c commit faa0494

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def longestPalindrome(self, s: str) -> str:
3+
"""
4+
Find the longest palindromic substring in the given string.
5+
Args:
6+
s: The input string.
7+
Returns:
8+
The longest palindromic substring in the input string.
9+
"""
10+
start = 0
11+
max_len = 1
12+
if len(s) <= 1:
13+
return s
14+
15+
def expand_around_center(left: int, right: int) -> tuple[int, int]:
16+
while left >= 0 and right < len(s) and s[left] == s[right]:
17+
left -= 1
18+
right += 1
19+
return right - left - 1, left + 1
20+
21+
for i in range(len(s)):
22+
length_odd, start_odd = expand_around_center(i, i)
23+
if length_odd > max_len:
24+
max_len = length_odd
25+
start = start_odd
26+
length_even, start_even = expand_around_center(i, i + 1)
27+
if length_even > max_len:
28+
max_len = length_even
29+
start = start_even
30+
return s[start:start + max_len]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import pytest
2+
3+
from solutions.longest_palindromic_substring_0005 import Solution
4+
5+
6+
@pytest.mark.parametrize('args, expected', [
7+
('babad', 'bab'),
8+
('cbbd', 'bb'),
9+
('a', 'a'),
10+
('ac', 'a')
11+
])
12+
def test_solution(args: str, expected: str) -> None:
13+
sol = Solution()
14+
assert sol.longestPalindrome(args) == expected

0 commit comments

Comments
 (0)