Example 1
- Input
- s = "bluecode", wordDict = ["blue", "code"]
- Output
- true
The word "blue" covers positions 0 through 3 and "code" covers positions 4 through 7. They meet at boundary 4 with no gap or overlap, covering the entire string.
Given a string and a dictionary of words that may be reused any number of times, decide whether the string can be cut into a sequence of dictionary words placed back to back with no gaps.
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
The same dictionary word may be reused multiple times, and the words must cover s exactly from the first character to the last with nothing left over.
Note that a greedy first match can be wrong: an early word may fit yet block every completion, while a different first word succeeds.
The word "blue" covers positions 0 through 3 and "code" covers positions 4 through 7. They meet at boundary 4 with no gap or overlap, covering the entire string.
Use "apple", then "pen", then "apple" again. The dictionary may supply the same word repeatedly; the full 13-character string is covered.
The prefix "catsand" can be formed as "cats" + "and" or "cat" + "sand", but its leftover "og" is not coverable. The substring "dog" starts after "catsan", which is not a breakable prefix, so finding "dog" alone does not complete the string.
The single character is one complete dictionary word. The empty-prefix base case lets the first word end at boundary 1.
Choosing the first matching word "abc" leaves an impossible "d". Backtrack and choose "ab" + "cd" instead; the first fitting prefix is not always the right one.
Place a boundary between words rather than committing to the first matching prefix. In Example 1, the empty prefix ends at boundary 0, "blue" reaches boundary 4, and "code" reaches boundary 8, covering all of "bluecode". A boundary is useful only if the entire prefix before it is already breakable. Different segmentations that reach the same boundary leave the same remaining suffix, so a single boolean per boundary removes repeated work. Dictionary entries describe reusable pieces, not a supply that gets consumed.
Reveal Recursive Splitting: intuition, complexity, and code
When a sequence must be tiled by allowed pieces, record which prefixes already tile cleanly and extend them piece by piece instead of re-splitting suffixes.