Skip to content

Commit 85a306c

Browse files
authored
Merge pull request #2405 from gyeo-ri/main
[gyeo-ri] WEEK 02 solutions
2 parents aa93b01 + 22fd8f1 commit 85a306c

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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)): 순차 탐색하는 비효율적 알고리즘
40+
class Solution:
41+
def longestPalindrome(self, s: str) -> str:
42+
answer = ""
43+
44+
for i in range(len(s)):
45+
for j in range(i, len(s)):
46+
subset = s[i : j + 1]
47+
48+
if subset == subset[::-1]:
49+
if len(answer) < len(subset):
50+
answer = subset
51+
return answer
52+
"""
53+
54+
55+
if __name__ == "__main__":
56+
test_cases = [
57+
("babad", ["bab", "aba"]),
58+
("bb", ["bb"]),
59+
("aaabaaa", ["aaabaaa"]),
60+
("c", ["c"]),
61+
("123a24542a0321", ["a24542a"]),
62+
]
63+
64+
solution = Solution()
65+
for idx, case_ in enumerate(test_cases):
66+
s, answers = case_
67+
result = solution.longestPalindrome(s)
68+
assert (
69+
result in answers
70+
), f"Test Case {idx} Failed: Expected one of {",".join(answers)}, Got {result}"

0 commit comments

Comments
 (0)