Dynamic programming · Medium
A compact event string has lost its separators. A parser must decide whether the complete string can be reconstructed by concatenating words from a supplied dictionary. Repeated dictionary use is allowed, and choosing the longest matching prefix first can lead to a dead end.
Return whether the entire text can be segmented into one or more dictionary words with no skipped or reordered characters.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ text: string, words: string[] }
Fields
- text is the string to segment; words is the reusable dictionary.
- Strings contain printable ASCII characters only. Comparisons are case-sensitive; spaces count as characters.
- Duplicate words have no effect. Empty dictionary words are ignored.
Output
Return value
- Return a boolean, not a segmentation. The empty text returns true using zero words.
- Every non-empty segment must equal a dictionary word. The same word may be used repeatedly.
Constraints
- 0 <= text.length <= 10000; 0 <= words.length <= 10000; each word has at most 100 characters; total dictionary characters <= 200000.
Examples
Example 1
{
"text": "cars",
"words": [
"car",
"ca",
"rs"
]
}Returns
trueExample 2
{
"text": "aaaa",
"words": [
"aa",
""
]
}Returns
trueRequired complexity
O(total dictionary characters + n × L) time and O(total dictionary characters + n) space with maximum word length L