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 |
31 |
Tags
- binary search
- tree
- Depth-first Search
- 문자열
- DP
- string
- 이진트리
- Medium
- binary tree
- matrix
- 미디움
- backtracking
- Python
- Array
- 리트코드
- dfs
- easy
- 중간
- hash table
- Binary
- list
- 재귀
- linked list
- recursive
- HashTable
- sorting
- 쉬움
- math
- two pointers
- leetcode
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 131(Palindrome Partitioning, Python) 본문
1. 문제 링크
LeetCode - The World's Leading Online Programming Learning Platform
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
2. 문제 설명
- 문자열 s가 주어졌을 때, 모든 substring이 palindrome하도록 s를 partition하라.
- 여기서 palindrome이란, 문자열을 거꾸로 해도, 기존 문자열과 동일한 문자열을 의미한다.
- ex. wow는 뒤집어도 wow다.
- 여기서 palindrome이란, 문자열을 거꾸로 해도, 기존 문자열과 동일한 문자열을 의미한다.
- 예제1) s = "aab"라면, output은 [["a","a","b"], ["aa","b"]]가 된다.
- 예제2) s = "a"라면, output은 [["a"]]가 된다.
3. 처음 풀이
- backtracker를 사용하여 dfs를 해결하는 것이 어느정도 유형화 된 느낌이다.
- 해당 문제도 backtracker를 활용하였고,
- path와 start를 argument로 한 함수 helper에 대해
- start포인트가 len(s)에 도달하면, 지금까지의 path를 output에 append하여 반환하고,
- 그 외의 경우에는,
- range(start, len(s))에 대하여,
- substring이 뒤집어도 동일한지 (substring == substring[::-1])를 체크하여,
- 동일하다면 path에 append하고,
- helper를 호출, 다시 path를 pop하는 방식으로 코드를 작성하였다.
- range(start, len(s))에 대하여,
- runtime은 70%정도 나왔다.
class Solution:
def partition(self, s: str) -> List[List[str]]:
output = []
lenth_s = len(s)
def helper(path,start):
if start == lenth_s:
output.append(path[:])
return
for i in range(start, len(s)):
substring = s[start:i+1]
if substring == substring[::-1]:
path.append(substring)
helper(path,i+1)
path.pop()
helper([],0)
return output
5. 배운 점
- slicing은 heavy한 연산이니, 아래처럼 하는 것보다, variable에 사용하는것이 낫다.
- 최대한 중복 계산을 피하기 위해 변수에 저장하는 것을 고려하자.
if s[start:i+1] == s[start:i+1][::-1]:
path.append(s[start:i+1])
helper(path,i+1)
path.pop()
- path.copy()보다 path[:]를 사용하는게 runtime관점에서 좋다.
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 349(Intersection of Two Arrays, Python) (1) | 2024.03.22 |
---|---|
LeetCode 137(Single Number II, Python) (0) | 2024.03.21 |
LeetCode 326(Power of Three, Python) (0) | 2024.03.13 |
LeetCode 292(Nim Game, Python) (0) | 2024.03.11 |
LeetCode 290(Word Pattern, Python) (0) | 2024.03.09 |