Unspaced Hashtag Split

Medium · 1-D Dynamic Programming · about 20 min

A social app shows hashtags with the spaces removed, like "applepenapple". Given the hashtag text and a list of known words, return True if text can be cut into a sequence of known words (a word may be used any number of times), otherwise False.

  • 0 <= len(text) <= 300, lowercase letters only. An empty hashtag counts as split (True).
  • 0 <= len(words) <= 50, each word has 1 to 20 lowercase letters.

Examples:

can_split_words("applepenapple", ["apple", "pen"]) → True

can_split_words("catsandog", ["cats", "dog", "sand", "and", "cat"]) → False

Hints

  • Ask a smaller question for every position: can the text up to here be split?
  • Position i is reachable if some earlier reachable position j has a known word from j to i.
  • The start (position 0) is always reachable. Put the words in a set for quick lookups.

Learn the pattern first: the 1-D Dynamic Programming lesson.

More 1-D Dynamic Programming problems