Splitting strings: word break and decode ways
🌍 In real life. A shop sign was painted without spaces: teaandcake. Can it be read as dictionary words (tea and cake)? And two friends send secret messages where A = 1, B = 2, …, Z = 26: the message 226 could be BBF (2 2 6), VF (22 6) or BZ (2 26). How many readings are there?
Both ask about the ways to cut a string into pieces. Trying every set of cuts is 2ⁿ⁻¹ possibilities; a 1D DP over the prefixes of the string answers in polynomial time (LeetCode 139 and 91).
The idea in one sentence: let the state be a prefix, the first i characters: it can be split (or read) if some last piece is valid and the prefix before that piece could be split (or read) too, so ok[i] and ways[i] are built from smaller prefixes.
Its words:
- prefix:
text[:i], the first i characters;ok[0]andways[0]are for the empty prefix - last piece: the final word (or the final 1 or 2 digits) of a split of the prefix
- base case: the empty prefix splits in exactly one way: no pieces at all
Step by step, the readings of 226:
ways[0] = 1: the empty start.- "2": the last digit 2 is a letter:
ways[1] = ways[0] = 1. - "22": last digit 2 →
ways[1]; last two digits 22 is a letter too →+ ways[0]: 2. - "226": last digit 6 →
ways[2] = 2; last two digits 26 →+ ways[1] = 1: 3.
Word break is the same shape. ok[i] asks: does text[:i] split into dictionary words? It does when, for some j, text[:j] splits (ok[j]) and text[j:i] is a word. One true j is enough, so the inner loop can stop at the first. To list how many splits there are, add up instead of stopping, just like ways.
Why it is correct. Every split of a prefix has a last piece, so grouping the splits by their last piece counts each exactly once (decode ways) or finds one if any exists (word break). The pieces before it form a split of a shorter prefix, which is already in the table.
What it costs, by counting. Decode ways: n prefixes, 2 checks each, O(n) (and only the last two values are ever read, so O(1) memory is possible). Word break: n prefixes, up to n cut points each, and slicing and hashing a piece of length up to L: about O(n² × L); checking only cuts within the longest word's length brings it down to O(n × L²).
def word_break(text, words):
words = set(words)
ok = [True] + [False] * len(text) # ok[i]: text[:i] splits into words
for i in range(1, len(text) + 1):
for j in range(i): # the last word would be text[j:i]
if ok[j] and text[j:i] in words:
ok[i] = True
break
return ok[-1]
def decode_ways(s):
ways = [1] + [0] * len(s) # ways[i]: ways to read s[:i]
for i in range(1, len(s) + 1):
if s[i - 1] != "0":
ways[i] += ways[i - 1] # the last letter is one digit
if i >= 2 and "10" <= s[i - 2:i] <= "26":
ways[i] += ways[i - 2] # the last letter is two digits
return ways[-1]
print(word_break("teaandcake", ["tea", "and", "cake", "an"]))
print(word_break("catsandog", ["cats", "dog", "sand", "and", "cat"]))
print(decode_ways("226"), decode_ways("106"), decode_ways("06"))Mistakes and edge cases.
- A greedy split. Taking the longest word first fails: for
aaabwith the wordsaaa,aaandab, takingaaaleavesb, which is stuck, whileaaleavesab, a word. The DP tries every last piece. - Zeros in decode ways. 0 alone is not a letter, and a two-digit piece starting with 0 (
06) isn't either: compare the text"10" <= piece <= "26", notint(piece) <= 26, which lets06through. - Forgetting the base case. With
ways[0] = 0(orok[0] = False) nothing can ever be built. - Recursion without a memo. The plain recursive version re-solves the same suffix many times: exponential. Add
@cache(Lesson 27.4) or use the table. - A list of words.
text[j:i] in wordson a list is O(len(words)) each time; turn it into a set first.
Quiz
What does this print?
def decode_ways(s): ways = [1] + [0] * len(s) # ways[i]: ways to read s[:i] for i in range(1, len(s) + 1): if s[i - 1] != "0": ways[i] += ways[i - 1] # the last letter is one digit if i >= 2 and "10" <= s[i - 2:i] <= "26": ways[i] += ways[i - 2] # the last letter is two digits return ways[-1] print(decode_ways("12"), decode_ways("11106"))In word break, what does ok[i] mean?
- The first i characters can be split into dictionary words
- The i-th character starts a word
- There are i words in the text
Why does taking the longest matching word first fail for word break?
- An early choice can leave a rest that can't be split, while a shorter word would have worked
- Long words are never in the dictionary
- It is too slow
decode_ways("106") should be 1 (only J F), but this gives 2. Which line is wrong?
def decode_ways(s): ways = [1] + [0] * len(s) for i in range(1, len(s) + 1): if s[i - 1] != "0": ways[i] += ways[i - 1] if i >= 2 and int(s[i - 2:i]) <= 26: ways[i] += ways[i - 2] return ways[-1]
Coding tasks
Write
word_break(text, words): True iftextcan be split into a sequence of words fromwords(a word may be used many times).Write
decode_ways(s): how many ways a string of digits can be read as letters with A = 1 … Z = 26.