Practice · Dynamic programming (1D) · 7 of 8

Split a String into Words

You are given a string s and a list of words wordDict. Return true if s can be cut into pieces so that every piece is a word in wordDict, and false otherwise.

You may use a word as many times as you like, and you don't have to use every word.

Example 1

Input
s = "sunflowerpot", wordDict = ["flower", "sun", "pot", "flowerpot"]
Output
true
sun + flower + pot works, and so does sun + flowerpot.

Example 2

Input
s = "carpet", wordDict = ["car", "carp", "pe"]
Output
false
After car or carp, what is left (pet or et) can't be made from the words.

Example 3

Input
s = "aaaaaaa", wordDict = ["aaa", "aaaa"]
Output
true
aaa + aaaa.

Constraints

  • s holds 1 to 300 lowercase letters.
  • wordDict holds 1 to 1000 different words, each of 1 to 20 lowercase letters.