边工作边刷题:70天一遍leetcode: day 20-2

Decode Ways

facebook以前特别爱考这题,不知道现在如何了。http://pastebin.com/Yfq8jKq7 (my code: list all possibilities, dp)

class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        def checkOne(c):
            if ord(c)<=ord('9') and ord(c)>ord('0'):
                return True
                
        def checkTwo(c1, c2):
            if (ord(c1)==ord('1') or
                (ord(c1)==ord('2') and 
                    ord(c2)>=ord('0') and ord(c2)<=ord('6'))): 
                        return True
        
        if not s: return 0
        dp_1 = 1 if checkOne(s[0]) else 0
        if len(s)<=1: return dp_1
        dp_2 = (dp_1 if checkOne(s[1]) else 0) + (1 if checkTwo(s[0], s[1]) else 0)
        
        for i in range(2, len(s)):
            dp_cur = dp_1 if checkTwo(s[i-1], s[i]) else 0
            dp_cur += dp_2 if checkOne(s[i]) else 0
            dp_1 = dp_2
            dp_2 = dp_cur
        
        return dp_2

posted @ 2016-04-29 10:00  absolute100  阅读(99)  评论(0编辑  收藏  举报