반응형
Word Break
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20sandwordDict[i]consist of only lowercase English letters.- All the strings of
wordDictare unique.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
dp = [False for _ in range(n + 1)]
dp[0] = True
wordSet = set(wordDict)
for i in range(1, n + 1) :
for j in range(i) :
if dp[j] and s[j:i] in wordSet :
dp[i] = True
break
return dp[-1]
다양한 방법으로 풀 수 있겠지만, DP로 해결하였다.
이중 for 문에서 i는 문자의 끝, j는 문자의 시작을 의미하고 dp[j]가 True 일때만 유효하므로 j부터 i까지 문자가 wordDict에 있으면 문자열 끝인 dp[i]에 True 를 적는다. 다음 체크포인트가 되겠지?
다른 테스트 케이스로 "aaaaaaa" 을 wordDict = ["aaaa", "aaa"]인 케이스가 있었다. 처음에 3번째 a에 True가 체크될 것이고 이후 4번째 a에도 True가 체크될 것이다. 그리고 6번째와 마지막 a에 True가 체크 될 것이다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 148. Sort List (0) | 2026.01.17 |
|---|---|
| [Leetcode/파이썬] 92. Reverse Linked List II (0) | 2026.01.17 |
| [Leetcode/파이썬] 79. Word Search (0) | 2026.01.11 |
| [Leetcode/파이썬] 909. Snakes and Ladders (0) | 2026.01.01 |
| [Leetcode/파이썬] 19. Remove Nth Node From End of List (0) | 2026.01.01 |