706. Digit Message Decodings

Medium3.5 points estimatedStringDynamic Programming3 hints

A radio operator receives a message as a string s of digits. The agreed code maps 1 to A, 2 to B, and so on up to 26 for Z. To read the message, the digit string is cut into consecutive pieces, and every piece must be a code between 1 and 26 written without a leading zero, so 05 is not a valid piece and a lone 0 is not either.

Return the number of different ways to cut s into valid pieces, modulo 1000000007. If no valid cutting exists, return 0. Two cuttings are different when they place their cut points differently.

Aim for time O(n) and extra space O(1), where n is the length of s.

Example 1

Input:
s = "1212"
Output:
5
Explanation:

The cuttings are 1-2-1-2, 12-1-2, 1-21-2, 1-2-12 and 12-12, so there are 5.

Example 2

Input:
s = "3010"
Output:
0
Explanation:

A lone 0 is not a code and 30 is above 26, so no cutting works and the answer is 0.

Constraints

1 ≤ n = s.length ≤ 105

s consists only of the digits 0 to 9.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…