Menu
CoddyTech

Word Break

You get a string s and a list of words wordDict. Return true if you can cut s into pieces that are all words from wordDict, and false otherwise.

The pieces keep their order and together use every letter of s exactly once. A word may be used any number of times, and you do not have to use every word.

Function

wordBreak(s: string, wordDict: string-array) → boolean
sstring
the string to cut into words
wordDictstring-array
the words you may use, each as often as you like
Returnsboolean
true if s can be cut into dictionary words, false otherwise

Constraints

  • 1 ≤ s.length ≤ 300
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • s and every word hold only lowercase English letters.
  • The words in wordDict are all different.

Examples

Input
s = "sunflowerseed"wordDict = ["sun", "flow", "flower", "seed"]
Output
true
Explanation
Cut it as sun, flower, seed. Taking flow after sun leaves er, which no word starts, so the first word that fits is not always the right one.
challenge icon

Follow-up

Return the fewest words a valid cut can use, or -1 if s cannot be cut. What changes in the table, and does the running time change?

Reset code
def wordBreak(s, wordDict):
    # Write code here

Test #1

Test #2

Test #3

Arguments

s = "sunflowerseed"
wordDict = ["sun", "flow", "flower", "seed"]

Expected Output

true