Algorithms · Level 3 Dynamic Programming

Word Break

Check whether a hashtag splits into dictionary words by recording which prefixes split cleanly, where grabbing the longest matching word fails.

  • ok[i]: the first i letters split into words
  • a word ending at i, and ok where it starts
  • the longest match first can fail

ok[i] says whether the first i letters split into words. It's true if a word ends at i and ok is true where that word starts. Trap: grabbing the longest (or first) matching word can leave letters that fit nothing.

# can we pay 0 to 7 with coins of 3 and 5?
C, ok = (3, 5), [True] + [False] * 7
for n in range(1, 8):
    ok[n] = any(n >= c and ok[n - c] for c in C)
ok  # True for 0, 3, 5 and 6

Write can_split(text, words): True if text is one or more words from words glued together (a word may repeat). Example: can_split('learnmapdev', ['learn', 'map', 'dev']) → True.

solution.py
Test Suites Pending
Output