Word Break
Problem
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
andwordDict[i]
consist of only lowercase English letters.- All the strings of
wordDict
are unique.
Solution
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function(s, wordDict) {
const dp = Array(s.length + 1).fill(false);
dp[0] = true;
const set = {};
for (const w of wordDict) {
set[w] = true;
}
for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
const substr = s.substring(j, i);
if (dp[j] && substr in set) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
};
We will implement a DP solution. Let dp[i]
be whether s[0:i]
can be segmented into a space-separated sequence of one or more dictionary words.
- For the base case, if
i = 0
, thendp[0]
is initialized totrue
sinces[0:0]
is the empty string. - For the recursive case, if there exists a split such that
dp[j] = true
ands[j:i]
is a word inset
, thendp[i] = true
(ie. there is a valid segmentation fors[0:i]
).