일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 315. Count of Smaller Numbers After Self
- t1
- DWG
- Protocol
- 운영체제
- Convert Sorted List to Binary Search Tree
- attribute
- Python
- 밴픽
- 109. Convert Sorted List to Binary Search Tree
- concurrency
- iterator
- 43. Multiply Strings
- Generator
- kaggle
- data science
- Decorator
- Substring with Concatenation of All Words
- 프로그래머스
- 컴퓨터의 구조
- 파이썬
- Regular Expression
- Class
- Python Implementation
- shiba
- 시바견
- Python Code
- 30. Substring with Concatenation of All Words
- 715. Range Module
- LeetCode
Archives
- Today
- Total
Scribbling
LeetCode: 132. Palindrome Partitioning II 본문
Computer Science/Coding Test
LeetCode: 132. Palindrome Partitioning II
focalpoint 2021. 11. 13. 12:53
1. Bottom-up Solution + predefining palindromic matrix
class Solution:
def minCut(self, s: str) -> int:
dp = self.build_palindrome(s)
n = len(s)
self.cut = [2002] * n
for end in range(n):
if dp[0][end]:
self.cut[end] = 0
continue
for start in range(1, end+1):
if dp[start][end]:
self.cut[end] = min(self.cut[end], self.cut[start-1] + 1)
return self.cut[-1]
def build_palindrome(self, word):
n = len(word)
dp = [[False] * n for _ in range(n)]
for end in range(n):
for start in range(end+1):
if word[end] == word[start] and (end - start <= 2 or dp[start+1][end-1]):
dp[start][end] = True
return dp
2. Top-down Solution + predefining palindromic matrix
class Solution:
def minCut(self, s: str) -> int:
self.dp = self.build_palindrome(s)
self.cut = [2001] * len(s)
self.helper(s, len(s)-1)
return self.cut[-1]
def helper(self, s, end):
if self.cut[end] != 2001:
return self.cut[end]
if end == 0:
self.cut[end] = 0
return 0
if self.dp[0][end]:
self.cut[end] = 0
return 0
for start in range(end, 0, -1):
if self.dp[start][end]:
self.cut[end] = min(self.cut[end], self.helper(s, start-1)+1)
return self.cut[end]
def build_palindrome(self, word):
n = len(word)
dp = [[False] * n for _ in range(n)]
for end in range(n):
for start in range(end+1):
if word[end] == word[start] and (end - start <= 2 or dp[start+1][end-1]):
dp[start][end] = True
return dp
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 354. Russian Doll Envelopes (0) | 2021.11.15 |
---|---|
LeetCode: 300. Longest Increasing Subsequence (0) | 2021.11.15 |
LeetCode: 131. Palindrome Partitioning (0) | 2021.11.13 |
LeetCode: 146. LRU Cache (0) | 2021.11.11 |
LeetCode: 130. Surrounded Regions (0) | 2021.11.10 |