Skip to content

Commit aced264

Browse files
committed
feat: solve #266 with python
1 parent 5874cd1 commit aced264

File tree

1 file changed

+53
-0
lines changed
  • longest-palindromic-substring

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from unittest import TestCase, main
2+
3+
4+
class Solution:
5+
def longestPalindrome(self, s: str) -> str:
6+
return self.solve_sliding_window(s)
7+
8+
"""
9+
Runtime: 47 ms (Beats 96.97%)
10+
Time Complexity: O(n ^ 3)
11+
- s의 길이를 n이라 하면, s의 길이 - 1 만큼 조회하는데 O(n - 1)
12+
- 각 문자마다 sliding_window를 2회 호출하는데, 각 호출마다 최대 s의 길이만큼 반복하므로, * 2 * O(n), upper bound
13+
- 반복 후 s를 slicing하는데 최대 * O(n), upper bound
14+
> O(n - 1) * (2 * O(n)) * O(n) ~= O(n ^ 3)
15+
16+
Memory: 16.54 MB (Beats 88.85%)
17+
Space Complexity: O(n)
18+
- sliding_window의 결과로 생성되는 문자열의 최대 길이는 n이고, 조회마다 2회 생성되므로 2 * O(n), upper bound
19+
> 2 * O(n) ~= O(n)
20+
"""
21+
def solve_sliding_window(self, s: str) -> str:
22+
23+
def sliding_window(left: int, right: int) -> str:
24+
while 0 <= left and right < len(s) and s[left] == s[right - 1]:
25+
left -= 1
26+
right += 1
27+
28+
return s[left + 1: right - 1]
29+
30+
if len(s) < 2 or s == s[::-1]:
31+
return s
32+
33+
result = ''
34+
for i in range(len(s) - 1):
35+
result = max(result, sliding_window(i, i + 1), sliding_window(i, i + 2), key=len)
36+
37+
return result
38+
39+
40+
class _LeetCodeTestCases(TestCase):
41+
def test_1(self):
42+
s = "babad"
43+
output = "bab"
44+
self.assertEqual(Solution().longestPalindrome(s), output)
45+
46+
def test_2(self):
47+
s = "cbbd"
48+
output = "bb"
49+
self.assertEqual(Solution().longestPalindrome(s), output)
50+
51+
52+
if __name__ == '__main__':
53+
main()

0 commit comments

Comments
 (0)