python solution O(1) space, beats 100%


  • 0
    I
    class Solution(object):
        def numDecodings(self, s):
            """
            :type s: str
            :rtype: int
            """
            if not s or s[0] == '0':
                return 0
                
            decode_2 = 0
            decode_1 = 1
            decode_n = 1
            # 10
            for i in xrange(1, len(s)):
                decode_n = 0
                if s[i] > '0':
                    decode_n += decode_1
                    
                if '10' <= s[i-1:i+1] <= '26':
                    if i - 1 == 0:
                        decode_n += 1
                    else:
                        decode_n += decode_2
                    
                decode_2 = decode_1
                decode_1 = decode_n
                
            return decode_n
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.