Overview
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.
The same word in the dictionary may be reused multiple times.
Constraints
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20sandwordDict[i]consist of lowercase English letters.- All strings in
wordDictare unique.
Examples
wordBreak("leetcode", ["leet", "code"]);
// => true ("leet" + "code")wordBreak("applepenapple", ["apple", "pen"]);
// => true ("apple" + "pen" + "apple")
wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]);
// => falseSolution
Reveal solution
function wordBreak(s, wordDict) {
const wordSet = new Set(wordDict);
const dp = new Array(s.length + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordSet.has(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
}Bottom-up DP. dp[i] is true if s[0..i) can be segmented. For each position, check all possible last words.
Resources
segment-words.js
Segment Words
mediumcodingAlgorithmsDynamic Programming
Overview
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.
The same word in the dictionary may be reused multiple times.
Constraints
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20sandwordDict[i]consist of lowercase English letters.- All strings in
wordDictare unique.
Examples
wordBreak("leetcode", ["leet", "code"]);
// => true ("leet" + "code")wordBreak("applepenapple", ["apple", "pen"]);
// => true ("apple" + "pen" + "apple")
wordBreak("catsandog", ["cats", "dog", "sand", "and", "cat"]);
// => falseSolution
Reveal solution
function wordBreak(s, wordDict) {
const wordSet = new Set(wordDict);
const dp = new Array(s.length + 1).fill(false);
dp[0] = true;
for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordSet.has(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
}Bottom-up DP. dp[i] is true if s[0..i) can be segmented. For each position, check all possible last words.
Resources
NameTopicDifficulty
103 of 103 problems