Decode Ways

Medium1-D dynamic programming

A message of capital letters was turned into digits with A = 1, B = 2, and so on up to Z = 26, and the digits were written down with nothing between them.

Given the digits s, return how many different letter messages could have produced them. A group of digits is a letter only if it is a number from 1 to 26 with no leading zero, so "05" is not a letter. If no message fits, return 0.

Examples

Example 1
Input:  s = "13"
Output: 2

AC (1, 3) or M (13).

Example 2
Input:  s = "2611"
Output: 4

2 6 1 1, 26 1 1, 2 6 11 and 26 11. 61 is too big to be a letter.

Constraints

  • 1 ≤ s.length ≤ 100
  • s holds digits only, and may start with a 0.

Stuck?

Hint 1

The last letter used either one digit or two. So the ways to read the first i digits are the ways for i - 1 (if digit i alone is a letter) plus the ways for i - 2 (if the last two digits make a letter).

Hint 2

A lone 0 is never a letter, and a two-digit group must be between 10 and 26. Keep the last two counts and walk along the string.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 12 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur