Algo-Sim › Dynamic Programming

Decode Ways

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Like Climbing Stairs with rules: the last letter used one digit (if it is not 0) or two digits (if they read 10–26).

Problem

Letters are encoded as numbers: A is 1, B is 2, …, Z is 26. Given a string of digits s, return how many ways it can be decoded back into letters. A part with a leading zero, such as 06, is not a valid code.

Constraints

Edge cases to test

Follow-up questions

What if * can be any digit 1–9?
Each state branches into the counts for single and pair digits with *, all mod 10⁹ + 7 (LC 639).
Why only two variables?
dp[i] depends on dp[i − 1] and dp[i − 2], like Climbing Stairs.

Solution

Java

public int numDecodings(String s) {
    int n = s.length();
    int[] dp = new int[n + 1];
    dp[0] = 1;
    for (int i = 1; i <= n; i++) {
        if (s.charAt(i - 1) != '0') {
            dp[i] += dp[i - 1];
        }
        if (i >= 2) {
            int two = Integer.parseInt(s.substring(i - 2, i));
            if (two >= 10 && two <= 26) dp[i] += dp[i - 2];
        }
    }
    return dp[n];
}

Python

def num_decodings(s):
    n = len(s)
    dp = [0] * (n + 1)
    dp[0] = 1
    for i in range(1, n + 1):
        if s[i - 1] != "0":
            dp[i] += dp[i - 1]
        if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:
            dp[i] += dp[i - 2]
    return dp[n]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int numDecodings(string &s) {
        int n = int(s.size());
        vector<int> dp = vector<int>(n + 1);
        dp[0] = 1;
        for (int i = 1; i <= n; i++) {
            if (s[i - 1] != '0') {
                dp[i] += dp[i - 1];
            }
            if (i >= 2) {
                int two = stoi(s.substr(i - 2, (i) - (i - 2)));
                if (two >= 10 && two <= 26)
                    dp[i] += dp[i - 2];
            }
        }
        return dp[n];
    }
};

More Dynamic Programming problems