Dynamic Programming
Decode Ways
DESCRIPTION (inspired by Leetcode.com)
Your are given a string s containing only digits. Write a function to return the number of ways to decode using the following mapping:
'1' -> "A" '2' -> "B" '3' -> "C" ... '26' -> "Z"
There may be multiple ways to decode a string. For example, "14" can be decoded as "AD" or "N".
Input:
s = 101
Output:
1
Explanation: The only way to decode it is "JA". "01" cannot be decoded into "A" as "1" and "01" are different.
Explanation
def num_decodings(s):if not s or s[0] == '0':return 0n = len(s)dp = [0] * (n + 1)dp[0], dp[1] = 1, 1for i in range(2, n + 1):digit = int(s[i - 1])if digit != 0:dp[i] += dp[i - 1]digit = int(s[i - 2:i])if 10 <= digit <= 26:dp[i] += dp[i - 2]return dp[n]
decode ways
0 / 1
Single Digit
def num_decodings(s):if not s or s[0] == '0':return 0n = len(s)dp = [0] * (n + 1)dp[0], dp[1] = 1, 1for i in range(2, n + 1):digit = int(s[i - 1])if digit != 0:dp[i] += dp[i - 1]digit = int(s[i - 2:i])if 10 <= digit <= 26:dp[i] += dp[i - 2]return dp[n]
i = 2
0 / 2
def num_decodings(s):if not s or s[0] == '0':return 0n = len(s)dp = [0] * (n + 1)dp[0], dp[1] = 1, 1for i in range(2, n + 1):digit = int(s[i - 1])if digit != 0:dp[i] += dp[i - 1]digit = int(s[i - 2:i])if 10 <= digit <= 26:dp[i] += dp[i - 2]return dp[n]
digit = 0
0 / 1
Double Digit
def num_decodings(s):if not s or s[0] == '0':return 0n = len(s)dp = [0] * (n + 1)dp[0], dp[1] = 1, 1for i in range(2, n + 1):digit = int(s[i - 1])if digit != 0:dp[i] += dp[i - 1]digit = int(s[i - 2:i])if 10 <= digit <= 26:dp[i] += dp[i - 2]return dp[n]
digit = 11
0 / 2
Solution
def num_decodings(s):if not s or s[0] == '0':return 0n = len(s)dp = [0] * (n + 1)dp[0], dp[1] = 1, 1for i in range(2, n + 1):digit = int(s[i - 1])if digit != 0:dp[i] += dp[i - 1]digit = int(s[i - 2:i])if 10 <= digit <= 26:dp[i] += dp[i - 2]return dp[n]
decode ways
0 / 20
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n) where n is the length of the string. We iterate through the string once.
Space Complexity: O(n) where n is the length of the string. We use an array of length n + 1 to store the number of ways to decode the first i characters of the string.
Mark as read
Unlock Premium Coding Content
On This Page
Your account is free and you can post anonymously if you choose.