LeetCode - 139. Word Break
Medium
題目
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.
解題思路
經典字串 DP 題
判斷 s 能不能被切成多個存在於 wordDict 裡的字串
DP 定義:
dp[i]:代表s[0...i-1]是否可以被成功切分
初始化:
dp[0] = true- 代表空字串可以被成功切分
先將
wordDict存進 unordered_map- 方便後面快速查詢某段 substring 是否存在於字典中
狀態轉移:
- 枚舉結尾位置
i - 再枚舉切割點
j - 如果:
dp[j] == true- 代表
s[0...j-1]可以被成功切分 - 且
s.substr(j, i-j)存在於wordDict - 代表
s[j...i-1]也是合法字串
- 那麼:
dp[i] = true
- 枚舉結尾位置
也就是說:
- 前半段可以被成功切分
- 後半段又是一個字典裡的字
- 所以目前這段也可以被成功切分
最後答案為:
dp[n]
Solution Code
Time Complexity
O(n^3)
Space Complexity
O(n + wordDict.length)
1 | |