Skip to main content

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 and wordDict[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, then dp[0] is initialized to true since s[0:0] is the empty string.
  • For the recursive case, if there exists a split such that dp[j] = true and s[j:i] is a word in set, then dp[i] = true (ie. there is a valid segmentation for s[0:i]).