Learn DSA
Depth-First Search
Greedy Algorithms
Decode Ways
DESCRIPTION (credit 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:
Output:
Explanation: The only way to decode it is "JA". "01" cannot be decoded into "A" as "1" and "01" are different.
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, determine the total number of ways to decode it. For example, given the encoded message "226", you should return 3 since it could be decoded as "BZ", "VF", and "BBF".
Run your code to see results here
Have suggestions or found something wrong?
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
Complexity Analysis
Login to track your progress
Your account is free and you can post anonymously if you choose.