Practice · Dynamic programming (1D) · 2 of 8

Count Ways to Decode Digits

A message of capital letters was turned into digits with A → 1, B → 2, …, Z → 26, and the codes were written one after another with no gaps. So "126" could have come from ABF (1 2 6), AZ (1 26) or LF (12 6).

Given the string of digits s, return the number of ways to decode it. No code starts with 0: "06" can't be read as F, and a 0 can't stand on its own, so some strings can't be decoded at all and the answer is 0.

Example 1

Input
s = "126"
Output
3
ABF (1 2 6), AZ (1 26) and LF (12 6).

Example 2

Input
s = "2101"
Output
1
The 0 must pair with the 1 before it, which leaves only 2 10 1 (BJA).

Example 3

Input
s = "30"
Output
0
30 is not a code, and 0 can't be read on its own.

Constraints

  • s holds 1 to 70 digits, and may contain 0s anywhere, including at the start.
  • The answer is below 2⁵³.