Decode Ways

You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping:

`"1" -> 'A'
"2" -> 'B'
...
"25" -> 'Y'
"26" -> 'Z'`

However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2" and "5" vs "25").

For example, "11106" can be decoded into:

  • "AAJF" with the grouping (1, 1, 10, 6)
  • "KJF" with the grouping (11, 10, 6)
  • The grouping (1, 11, 06) is invalid because "06" is not a valid code (only "6" is valid).

Note: there may be strings that are impossible to decode.

Given a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0.

The test cases are generated so that the answer fits in a 32-bit integer.

Example 1
Inputs = "12"
Output2
The string can be decoded as "AB" using 1 and 2, or as "L" using 12.
Example 2
Inputs = "226"
Output3
The string can be decoded as "BZ" using 2 and 26, "VF" using 22 and 6, or "BBF" using 2, 2, and 6.

Constraints

  • 1 <= s.length <= 100
  • s contains only digits and may contain leading zero(s).
  • The answer is guaranteed to fit in a 32-bit integer.

Asked at 23 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate