139. Word Break
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- 1-D Dynamic Programming
- Time
- O(len * maxWordLen)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven a string and a dictionary of words, determine whether the string can be fully segmented into a sequence of one or more dictionary words.
Approach
- Use a boolean DP array where
dp[i]means the firsticharacters ofscan be segmented using dictionary words. - Base case:
dp[0] = true(empty prefix is always valid). - For each position
i, ifdp[i]is true, scan forward using the dictionary (stored in a hash set) to markdp[j]true for everyj > iwheres[i..j-1]is a word. - Bounding the inner scan by the maximum word length avoids redundant substring checks and keeps the approach efficient.
#include <string>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
int maxLen = 0;
unordered_set<string> dict;
for (const string& w : wordDict) {
dict.insert(w);
maxLen = max(maxLen, (int)w.size());
}
// dp[i] == true => s[0..i-1] can be segmented into dictionary words
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 1; i <= n; ++i) {
// Try every split point j where s[j..i-1] might be a word
for (int j = max(0, i - maxLen); j < i; ++j) {
if (dp[j] && dict.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
};
Time O(n * L) where n is the length of s and L is the maximum word length in the dictionary (bounds the inner loop; each substr check is O(L)) Space O(W * L + n) for the hash set storing all dictionary words plus the DP array
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
struct TrieNode {
TrieNode* children[26];
bool isEnd=false;
};
class Solution {
TrieNode* root=new TrieNode();
void insert(const string& word){
TrieNode* node=root;
for(char c: word){
if(!node->children[c-'a']){
node->children[c-'a']=new TrieNode();
}
node=node->children[c-'a'];
}
node->isEnd=true;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
// uset: store words
// dp[i]: dp[1...i] can be made up by words
// maxWordLen
// every time, we check dp[i-1]~dp[i-maxWordLen] exist in uset
// return dp[len]
// int len=s.length();
// int maxWordLen=INT_MIN;
// unordered_set<string_view> uset(wordDict.begin(), wordDict.end()); // n elements
// vector<bool> dp(len+1, false);
// for(const string& w: wordDict){
// maxWordLen=max(maxWordLen, (int)w.length());
// }
// dp[0]=true;
// string_view sv(s);
// for(int i=1; i<=len; ++i){
// for(int j=i-1; j>=0; --j){
// if(!dp[j] || i-j>maxWordLen){ // cur string len = i-j
// continue;
// }
// if(uset.count(sv.substr(j, i-j))){
// dp[i]=true;
// break;
// }
// }
// }
// return dp[len];
int len=s.length();
vector<bool> dp(len+1, false);
for(const string& w: wordDict){
insert(w);
}
dp[0]=true;
for(int i=0; i<len; ++i){
if(!dp[i]){
continue;
}
TrieNode* tmp=root;
for(int j=i; j<len; ++j){
int cur=s[j]-'a';
if(!tmp->children[cur]){
break;
}
tmp=tmp->children[cur];
if(tmp->isEnd){
dp[j+1]=true;
}
}
}
return dp[len];
}
};
// Time Complexity: O(len * maxWordLen)
// Space Complexity: O(N) for dp array and O(M) for unordered_set Time O(len * maxWordLen) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.