☰ All problems

58. Word Break

Given a string s and a list of dictionary words wordDict, return true if s can be cut into a sequence of one or more pieces where every piece is a dictionary word.

A dictionary word may be used any number of times, and not every word has to be used.

Example 1
Input: s = "icecreamcone", wordDict = ["ice","cream","cone","icecream"]
Output: true

Explanation: "ice" + "cream" + "cone" works (so does "icecream" + "cone").

Example 2
Input: s = "catcat", wordDict = ["cat"]
Output: true

Explanation: The same word can be reused.

Example 3
Input: s = "dogsandcat", wordDict = ["dog","dogs","sand","and","cats"]
Output: false

Explanation: Both "dog" + "sand" and "dogs" + "and" leave "cat", which is not in the dictionary.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and every word consist of lowercase English letters
  • All words in wordDict are distinct

Follow-up: How would you return every possible segmentation instead of just whether one exists?

💡 Hint 1

Trying every possible first word and recursing is correct but can be exponential: the same suffix gets re-checked many times.

💡 Hint 2

Let ok[i] mean "the first i characters can be segmented". ok[0] is true.

💡 Hint 3

ok[i] is true if some j < i has ok[j] true and s.slice(j, i) in the dictionary. Put the words in a hash set, and only look back as far as the longest word.

/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {boolean}
 */
function wordBreak(s, wordDict) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc