LeetCode Decode Ways

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.