Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- 이분 탐색(Binary Search)
- 이분 그래프(Bipartite Graph)
- 백준 17608번
- 위상 정렬(Topological Sort)
- 백준 1707번
- 동적 프로그래밍(Dynamic Programming)
- 스택(Stack)
- 그리디 알고리즘(Greedy Algorithm)
- 알고리즘 개념
- 백준 18352번
- 큐(Queue)
- 백준 2504번
- 분할 정복(Divide and Conquer)
- 백준 1948번
- 다익스트라 알고리즘(Dijkstra Algorithm)
- BFS
- 플로이드 워셜 알고리즘(Floyd-Warshall Algorithm)
- 백준 10000번
- 위상 정렬(Topology Sort)
- 백준 21606번
- 그래프(Graph)
- 백준 2812번
- DFS
- 백준 9012번
- DFS(Depth First Search)
- 백준 2261번
- DFS & BFS
- BFS(Breadth First Search)
- 백준 2493번
- 트리(Tree)
Archives
- Today
- Total
Always Be Wise
문자열 조작 : 가장 긴 팰린드롬 부분 문자열(리트코드 5번) 본문
728x90
▶ 문제 : https://leetcode.com/problems/longest-palindromic-substring/
Longest Palindromic Substring - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
##### 문제 #####
가장 긴 팰린드롬 부분 문자열을 출력하라.
##### 입력 #####
"babad"
##### 출력 #####
"bab"
▶ 접근 방법
팰린드롬이 가능한 경우의 문자열을 찾고 해당 문자열을 확장하는 식의 풀이로 접근하였다.
홀수 일 때와 짝수 일때에 해당하는 투포인터를 만들어 문자열을 살펴본다.
해당 포인터 범위 안에 들어온 문자열이 팰린드롬인 경우 그 자리에 멈추고, 투포인터를 확장한다.
▶ 풀이 코드
ex_string = "babad"
def longest_palindrome(string: str) -> str:
def expand(left:int, right: int) -> str:
while left >= 0 and right < len(string) and string[left] == string[right]:
left -= 1
right += 1
return string[left + 1:right]
if len(string) < 2 or string == string[::-1]:
return string
result = ''
for i in range(len(string) - 1):
result = max(result, expand(i, i + 1), expand(i, i + 2), key=len)
return result
print(longest_palindrome(ex_string))
▶ 관련 링크
'알고리즘 > 리트코드' 카테고리의 다른 글
| 배열 : 빗물 트래핑(리트코드 42번) (0) | 2021.12.15 |
|---|---|
| 배열 : 두 수의 합(리트코드 1번) (0) | 2021.12.15 |
| 문자열 조작 : 그룹 애너그램(리트코드 49번) (0) | 2021.12.14 |
| 문자열 조작 : 가장 흔한 단어(리트코드 819번) (0) | 2021.12.14 |
| 문자열 조작 : 로그 파일 재정렬(리트코드 937번) (0) | 2021.12.14 |