LeetCode 91 LintCode 512 – Python 3 (Week 09 – 07)

Solution 1: Use dp

class Solution:
    def numDecodings(self, s: str) -> int:
        if len(s) == 0 or s[0] == '0': return 0
        if len(s) == 1: return 1
        
        w1, w2 = 1, 1
        for i in range(1, len(s)):
            w = 0
            if s[i] == '0' and not 10 <= int(s[i-1 : i+1]) <= 26:
                return 0
            if s[i] != '0':
                w = w1
            if 10 <= int(s[i-1 : i+1]) <= 26:
                w += w2
            w2 = w1
            w1 = w
            
        return w1

Time complexity is O(n). Time complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started