Menu
CoddyTech

Word Break

You get a string s and a list of words wordDict. Return true if you can cut s into pieces so that every piece is a word 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 leads nowhere, since no word starts with the er that is left, so the first word that fits is not always the right one.

lock icon+21 hidden tests on Submit

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 cases

Case 1

Case 2

Case 3

Input

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

Expected

true