Question 91 Decode Ways

Question:

https://leetcode.com/problems/decode-ways/

 

My code

class Solution:
    def numDecodings(self, s: str) -> int:
# First we finish the part that the length of the string is 1
        if len(s) ==1:
            if int(s[0])== 0:
                return 0
            else:
                return 1
        else: # we then finish the part which has length larger than 1
            if int(s[0]) == 0:
                Mat = [0]*len(s)
            else:
                Mat = [1]*len(s)
            for StringNum in range(1,len(s)):
                if int(s[StringNum-1]) == 0:
                    if int(s[StringNum]) == 0:
                        Mat[StringNum] = 0
                    else:
                        if StringNum ==1:
                            Mat[StringNum]= 0
                        else:
                            Mat[StringNum] = Mat[StringNum-1] 
                elif int(s[StringNum-1])==1:
                    if int(s[StringNum])==0:
                        if StringNum == 1:
                            Mat[StringNum] = 1
                        else:
                            Mat[StringNum] = Mat[StringNum-2]
                    else:
                        if StringNum ==1:
                            Mat[StringNum] = 2
                        else:
                            Mat[StringNum] = Mat[StringNum-1]+Mat[StringNum-2]
                elif int(s[StringNum-1]) ==2:
                    if int(s[StringNum]) == 0:
                        if StringNum ==1:
                            Mat[StringNum] = 1
                        else:
                            Mat[StringNum] = Mat[StringNum-2]
                    elif int(s[StringNum]) >=7:
                        if StringNum ==1:
                            Mat[StringNum] =1
                        else:
                            Mat[StringNum] = Mat[StringNum-1]
                    else:
                        if StringNum ==1:
                            Mat[StringNum] = 2
                        else:
                            Mat[StringNum] = Mat[StringNum-1]+ Mat[StringNum-2]
                else:
                    if int(s[StringNum]) == 0:
                        Mat[StringNum] = 0
                    else:
                        if StringNum == 1:
                            Mat[StringNum] = 1
                        else:
                            Mat[StringNum] = Mat[StringNum-1]
        
        return Mat[len(s)-1]

Explanation:

The Structure of the code is a little difficult to explain in words. There will be (If I do not forget) a full chart to illustrate the whole idea.

Leave a comment