Skip to content
BytePatterns

Sentence Segmentation

MediumDynamic Programming#bottom-up-dp#hash-set~30m

Problem

Given a string with no spaces and a dictionary of words, decide whether the string can be cut into a sequence of dictionary words placed end to end. Words may be reused as often as needed, and every character must belong to exactly one word. Return true when such a cut exists.

Examples

Input:  text = applepen, words = [apple, pen]
Output: True
Why:    the cut apple + pen uses every character
Input:  text = applepin, words = [apple, pen]
Output: False
Why:    the tail pin is not a dictionary word
Input:  text = "", words = [apple]
Output: True
Why:    edge case, an empty string is already fully covered by zero words

Hints

0 / 3

Stuck on the idea rather than the code? Top-Down vs Bottom-Up covers it.