Chat app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-91dp
A chat app stores each sticker reaction as a number from 1 to 26, one number for each sticker in a small pack. An old log writes several reactions one after another as a string of digits, with no separators between them. The string 226 could be the reactions 2, 2, 6, or 22 and 6, or 2 and 26.
Your team lead asks: "In how many ways could this log have been written?"
Write count_readings(code).
code is a string of digits. A reading cuts it into pieces. Each piece is a number from 1 to 26 written without a leading zero.0 alone is not a piece, and neither is 06. A piece such as 10 or 20 is fine.Input: code = "226"
Output: 3Let ways[i] be the number of readings of the first i digits. The last piece of those digits is either the last digit alone, or the last two digits together.
The last digit alone adds ways[i - 1], unless that digit is 0. The last two digits add ways[i - 2], when they read 10 to 26. So ways[i] is the sum of the two.
| i | Digits read | Last digit | Ways if it stands alone | Last two digits | Ways if they are one piece | ways[i] |
|---|---|---|---|---|---|---|
| 0 | none | 1 | ||||
| 1 | 2 |
2 | 1 | none | 0 | 1 |
| 2 | 22 |
2 | 1 | 22 | 1 | 2 |
| 3 | 226 |
6 | 2 | 26 | 1 | 3 |
The answer is ways[3] = 3: the readings are 2, 2, 6 and 22, 6 and 2, 26.
Input: code = "2101"
Output: 1Only one reading works: 2, 10, 1. The pieces 21, 0, 1 and 2, 1, 0, 1 both need a lone 0, which is not a piece.
Input: code = "06"
Output: 0The string starts with 0. It cannot stand alone and 06 has a leading zero, so there is no reading.
1 ≤ len(code) ≤ 60code has only the digits 0 to 9.There are at most 60 digits. Listing every reading can take as many steps as there are readings: 2,504,730,781,961 for 60 ones. A table with one entry for each prefix has 61 entries. The answer needs 64-bit integers, because it passes 2 billion at about 45 digits.