LeetCode - 139. Word Break

LeetCode - 139. Word Break

LAVI

Medium

139. 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 <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
vector<bool> dp(n+1, false);

unordered_map<string, bool> mp;
for(auto word: wordDict) mp[word] = true;

dp[0] = true;

for(int i = 1; i <= n; ++i){
for(int j = 0; j < i; ++j){
// dp[j] = true 代表: s[0...j-1] 可以被成功切分
// mp[s.substr(j, i-j)] 代表: s[j...i-1] 是不是 wordDict 裡的字串
if(dp[j] && mp[s.substr(j, i-j)]) dp[i] = true;
}
}
return dp[n];
}
};
On this page
LeetCode - 139. Word Break