LeetCode Decode Ways
Decode Ways for solving LeetCode Problems
Original question
Now there is a correspondence between the following letters and numbers: 1-A, 2-B ,... 26-Z. Given a string composed of digits, determine the number of different types of strings that can be converted according to the above ing.
Note:
If the character cannot be converted normally, for example, "70", 0 is returned.
Example:
Input: s = "12"
Output: 2 (including "AB" (1 2) and "L" (12 ))
Solutions
The first thought was dynamic planning. First, I wrote a previous version. I had to discuss complicated classification, and the code was messy. Later I found it easier to traverse from the back. Let's take a look at the recursive formula. Assume that the original string is "y231" and add a number before it to get "xy231". If x is not 0, if "xy" is not between 1 and 26, the original Conversion Type remains unchanged, but an x-converted letter is added before each string. If "xy" is between 1 and 26, in addition to adding the x-converted letters before each character string, it may also be adding the "xy" converted letters before the "231" converted string. If x is equal to 0, it is an invalid string, and the default value is 0. But do not jump out of the loop, because adding a number above may make the string legal.
AC Source Code
class Solution(object): def numDecodings(self, s): """ :type s: str :rtype: int """ length = len(s) if length == 0: return 0 dp = [0 for __ in range(length + 1)] dp[length] = 1 dp[length - 1] = 1 if s[length - 1] != '0' else 0 for i in range(length - 2, -1, -1): if s[i] != '0': dp[i] = dp[i + 1] + dp[i + 2] if int(s[i:i + 2]) <= 26 else dp[i + 1] return dp[0]if __name__ == "__main__": assert Solution().numDecodings("110") == 1 assert Solution().numDecodings("40") == 0