Skip to content

Commit bff8540

Browse files
committed
feat: add longest palindromic substring solution
1 parent 010dc6d commit bff8540

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def is_palindrome(self, s: str) -> bool:
3+
return s == s[::-1]
4+
5+
def longestPalindrome(self, s: str) -> str:
6+
"""
7+
- Idea: ์•„๋ž˜์˜ ๋ฐฉ๋ฒ•์œผ๋กœ ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์—์„œ ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ์ฐพ๋Š”๋‹ค.
8+
1. ๋ชจ๋“  ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด ์ƒ์„ฑ
9+
2. ๊ฐ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ํŒฐ๋ฆฐ๋“œ๋กฌ์ธ์ง€ ํ™•์ธ
10+
3. ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ์ €์žฅํ•˜๊ณ  ๋ฐ˜ํ™˜
11+
- Time Complexity: O(n^3). n์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
12+
๋ชจ๋“  ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ๊ตฌํ•˜๋Š”๋ฐ O(n^2), ๊ฐ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ด ํŒฐ๋ฆฐ๋“œ๋กฌ์ธ์ง€ ์•Œ์•„๋‚ด๋Š”๋ฐ O(n).
13+
๊ฒฐ๊ตญ O(n^3)์˜ ์‹œ๊ฐ„์ด ์†Œ์š”๋œ๋‹ค.
14+
- Space Complexity: O(n). n์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
15+
ํŒฐ๋ฆฐ๋“œ๋กฌ์ธ์ง€ ํ™•์ธํ•  ๋•Œ ๋ฌธ์ž์—ด ์Šฌ๋ผ์ด์‹ฑ์„ ์‚ฌ์šฉํ•˜๋Š”๋ฐ,
16+
์ตœ์•…์˜ ๊ฒฝ์šฐ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ์ž…๋ ฅ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด์™€ ๊ฐ™์•„
17+
๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” O(n)์ด๋‹ค.
18+
"""
19+
20+
result = s[0]
21+
22+
for i in range(len(s) - 1):
23+
for j in range(i + 1, len(s) + 1):
24+
if j - i <= len(result):
25+
continue
26+
27+
if self.is_palindrome(s[i:j]) and (j - i) > len(result):
28+
result = s[i:j]
29+
30+
return result

0 commit comments

Comments
ย (0)