Decode Ways

Question (LC.91)

Given a string of digits, return the number of ways that you can partition it.

Example

Always think about edge cases before writing code. At least try 3 cases.

I: "12"
O: 2 because 12| or 1|2
I: "000"
O: 0
I: "02134234"
O: 0
base case
valid single digit
return 1
valid double digit
return 1
else return 0

if valid double digit
    return decode(n-1) + decode(n-2);
else if valid single digit
    return decode(n-1)
else 
    return 0

DP Approach

This is a maximization problem. We want to return the miximum number of solutions. We can clearly see some subtrees are repeating for example [1][2][1]31 and [12][1]31

Code

Validating the digit turns out to be the biggest challenge of this question.

Time & Space Complexity

O(n) time and O(n) space. Space can be constant.

Follow Up (LC.639)

Now the encoded string can also contain the character '*', which can be treated as any numbers from 1 to 9.

Example

Analysis

Last updated