Word Break

Implement wordBreak

Given a string s and a dictionary of words wordDict, determine whether s can be broken into consecutive dictionary words with no leftover characters — the same word can be reused as many times as the split calls for. The naive way tries every possible split point recursively, but the same starting position gets re-explored again and again through different earlier splits — that's what makes it exponential. Tracking, for every position, whether the prefix up to there is reachable at all (a simple boolean array) turns that repeated work into a single pass: once a position is known reachable, walking forward through a trie of the dictionary finds every word that starts there in one sweep, marking each landing spot reachable too.

Example 1:

Input: s = "leetcode", wordDict = ["leet","code"]

Output: true

Example 2:

Input: s = "applepenapple", wordDict = ["apple","pen"]

Output: true

Example 3:

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]

Output: false

+ 10 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 300
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • s and wordDict[i] consist of lowercase English letters
  • all strings in wordDict are unique

s =

leetcode

wordDict =

["leet", "code"]