| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- DWG
- 43. Multiply Strings
- 109. Convert Sorted List to Binary Search Tree
- kaggle
- Generator
- LeetCode
- Python Code
- iterator
- Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- 30. Substring with Concatenation of All Words
- Convert Sorted List to Binary Search Tree
- Decorator
- 파이썬
- 715. Range Module
- shiba
- 시바견
- t1
- concurrency
- attribute
- 운영체제
- Python Implementation
- Python
- Class
- Protocol
- 밴픽
- Regular Expression
- data science
- 프로그래머스
- 컴퓨터의 구조
Archives
- Today
- Total
Scribbling
LeetCode: 139. Word Break 본문
단어를 분해하거나 단어에서 단어를 찾는 문제를 다룰 때 가장 먼저 해볼만한 접근은,
분해 대상 단어를 한글짜 단위로 확인해가면서 완전탐색하는 것이다.
아래는 완전 탐색 코드이다.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
self.wordDict = set(wordDict)
return self.dfs(s)
def dfs(self, s):
if not s:
return True
for i in range(1, len(s)+1):
if s[:i] in self.wordDict:
if self.dfs(s[i:]):
return True
return False
제출해보면...?
타임 아웃이다.
생각해보면 dfs의 변수로 들어오는 s가 한번 계산된 경우, 추후 같은 s에 대해 dfs를 계산할 필요가 없다.
이점에 착안하면 아래처럼 코드를 변경할 수 있다.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
self.wordDict = set(wordDict)
self.dp = set()
return self.dfs(s)
def dfs(self, s):
if not s:
return True
if s in self.dp:
return False
for i in range(1, len(s)+1):
if s[:i] in self.wordDict:
if self.dfs(s[i:]):
return True
self.dp.add(s)
return False'Computer Science > Coding Test' 카테고리의 다른 글
| LeetCode: 143. Reorder List (0) | 2021.11.22 |
|---|---|
| LeetCode: 140. Word Break II (0) | 2021.11.22 |
| LeetCode: 138. Copy List with Random Pointer (0) | 2021.11.16 |
| LeetCode: 295. Find Median from Data Stream (0) | 2021.11.16 |
| LeetCode: 347. Top K Frequent Elements (0) | 2021.11.15 |