일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 109. Convert Sorted List to Binary Search Tree
- 운영체제
- Generator
- Convert Sorted List to Binary Search Tree
- Class
- Python
- 프로그래머스
- 30. Substring with Concatenation of All Words
- Python Implementation
- kaggle
- data science
- DWG
- LeetCode
- Python Code
- 43. Multiply Strings
- attribute
- iterator
- 715. Range Module
- t1
- Substring with Concatenation of All Words
- shiba
- 315. Count of Smaller Numbers After Self
- 시바견
- concurrency
- Protocol
- 밴픽
- Regular Expression
- 파이썬
- Decorator
- 컴퓨터의 구조
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 |