# 139. Word Break

Given a non-empty string  s  and a dictionary  wordDict  containing a list of non-empty words, determine if  s  can be segmented into a space-separated sequence of one or more dictionary words.

Note:

• The same word in the dictionary may be reused multiple times in the segmentation.
• You may assume the dictionary does not contain duplicate words.

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
``````

``````class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<int> memo(s.size(), -1);
return check(s, wordSet, 0, memo);
}
bool check(string s, unordered_set<string>& wordSet, int start, vector<int>& memo) {
if (start >= s.size()) return true;
if (memo[start] != -1) return memo[start];
for (int i = start + 1; i <= s.size(); ++i) {
if (wordSet.count(s.substr(start, i - start)) && check(s, wordSet, i, memo)) {
return memo[start] = 1;
}
}
return memo[start] = 0;
}
};
``````

``````class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1);
dp[0] = true;
for (int i = 0; i < dp.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && wordSet.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp.back();
}
};
``````

le e

lee ee e

leet

leetc eetc etc tc c

leetco eetco etco tco co o

leetcod eetcod etcod tcod cod od d

leetcode eetcode etcode tcode code

T F F F T F F F T

``````class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<bool> visited(s.size());
queue<int> q{{0}};
while (!q.empty()) {
int start = q.front(); q.pop();
if (!visited[start]) {
for (int i = start + 1; i <= s.size(); ++i) {
if (wordSet.count(s.substr(start, i - start))) {
q.push(i);
if (i == s.size()) return true;
}
}
visited[start] = true;
}
}
return false;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/139

https://leetcode.com/problems/word-break/

https://leetcode.com/problems/word-break/discuss/43797/A-solution-using-BFS

https://leetcode.com/problems/word-break/discuss/43886/Evolve-from-brute-force-to-optimal-a-review-of-all-solutions

Word Break II

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation