Word Break

Medium Tries AI round

s is a string of lowercase letters, and wordDict is a list of different words, also of lowercase letters.

To cut `s` into words is to split it into pieces, in order and with nothing left over, so that every piece is a word of wordDict. A word may be used any number of times, or not at all.

Return true if s can be cut into words, and false if it cannot.

Example 1

Input: s = "bookshelfbook", wordDict = ["book","shelf","books","elf"]
Output: true

Cut it as book, shelf and book again: every piece is a word, and a word may be used twice. Starting with books instead leaves helfbook, which no word begins, but one way is enough.

Example 2

Input: s = "nightowl", wordDict = ["night","nigh","tow","owls"]
Output: false

Example 3

Input: s = "ababab", wordDict = ["ab","aba","bab"]
Output: true

Constraints

  • 1 ≤ s.length ≤ 400
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • s and wordDict[i] are lowercase English letters
  • The words in wordDict are all different

Watch the explanation

More Tries

All Tries problems