Skip to content

Commit 336ebfc

Browse files
committed
fix: 중심 확장 알고리즘 사용
1 parent 33d0d79 commit 336ebfc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

longest-palindromic-substring/gyeo-ri.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,42 @@
1+
"""
2+
[결과 요약]
3+
# 재시도횟수: 4회
4+
1. 모든 문자열 조합을 계산하기(O(n^3))
5+
2. 중심 확장(O(n^2)): 문자열을 순서대로 순회하며 중심을 기준으로 좌우 대칭 비교"""
6+
7+
8+
class Solution:
9+
def longestPalindrome(self, s: str) -> str:
10+
def _expand_around(left, right) -> tuple[int, int]:
11+
while left >= 0 and right < length_s and s[left] == s[right]:
12+
left -= 1
13+
right += 1
14+
return left + 1, right - 1
15+
16+
# 초깃값
17+
length_s = len(s)
18+
best_left, best_right = 0, 0
19+
20+
# 1. 중심을 한 칸씩 이동하면서 반복하기
21+
for i in range(len(s)):
22+
# 2. 짝수/홀수 각각에 대해 탐색하기
23+
odd_left, odd_right = _expand_around(i, i)
24+
even_left, even_right = _expand_around(i, i + 1)
25+
26+
best_length = best_right - best_left
27+
odd_length = odd_right - odd_left
28+
even_length = even_right - even_left
29+
30+
if odd_length > best_length:
31+
best_left, best_right = odd_left, odd_right
32+
if even_length > best_length:
33+
best_left, best_right = even_left, even_right
34+
35+
return s[best_left : best_right + 1]
36+
37+
38+
"""
39+
#1. 브루트포스(O(n^3)): 순차 탐색하는 비효율적 알고리즘
140
class Solution:
241
def longestPalindrome(self, s: str) -> str:
342
answer = ""
@@ -10,6 +49,7 @@ def longestPalindrome(self, s: str) -> str:
1049
if len(answer) < len(subset):
1150
answer = subset
1251
return answer
52+
"""
1353

1454

1555
if __name__ == "__main__":

0 commit comments

Comments
 (0)