Overview
This problem is similar to the Fibonacci sequence but with constraints. At each step, we can either take 1 digit or 2 digits to decode.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given a string of digits, find the number of ways to decode it into letters ('A' = 1, 'B' = 2 ... 'Z' = 26).
This problem is similar to the Fibonacci sequence but with constraints. At each step, we can either take 1 digit or 2 digits to decode.
Let `dp[i]` be the number of ways to decode the prefix of the string of length `i`.
If the 1-digit substring `s[i-1:i]` is between "1" and "9", it can be decoded on its own. We add `dp[i-1]` to `dp[i]`.
If the 2-digit substring `s[i-2:i]` is between "10" and "26", it forms a valid letter. We add `dp[i-2]` to `dp[i]`.