Skip to content

Commit e63bfbc

Browse files
committed
solve: Longest Palindromic Substring
1 parent d6dd1f8 commit e63bfbc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Constraints:
3+
- 1 <= s.length <= 1000
4+
- s consist of only digits and English letters.
5+
6+
Time Complexity: O(n^3)
7+
- ๋ชจ๋“  ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ๊ตฌํ•  ๋•Œ O(n^2)
8+
- ๊ฐ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ํŒฐ๋ฆฐ๋“œ๋กฌ์ธ์ง€๋ฅผ ์•Œ์•„๋‚ผ ๋•Œ O(n)
9+
10+
Space Complexity: O(1)
11+
12+
Note:
13+
- ๋” ํšจ์œจ์ ์ธ ๋ฐฉ๋ฒ• ์ƒ๊ฐํ•ด๋ณด๊ธฐ/์ฐพ์•„๋ณด๊ธฐ
14+
"""
15+
# Solution 1: Brute force
16+
# ๋ฌธ์ž์—ด์˜ ์‹œ์ž‘๊ฐ’๊ณผ ๋๊ฐ’์„ ์ด์šฉํ•˜์—ฌ ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์œผ๋กœ ์—…๋ฐ์ดํŠธํ•˜๋Š” ๋ฐฉ์‹
17+
class Solution:
18+
def longestPalindrome(self, s: str) -> str:
19+
longest_palindrome = ""
20+
max_len = 0
21+
22+
for i in range(len(s)):
23+
for j in range(i, len(s)):
24+
substr = s[i:j+1]
25+
26+
if substr == substr[::-1]:
27+
if len(substr) > max_len:
28+
max_len = len(substr)
29+
longest_palindrome = substr
30+
31+
return longest_palindrome

0 commit comments

Comments
ย (0)