LC

P31. Decode Ways

这道题主要的坑在于,怎么去处理含有0的情况。这里有个小技巧处理dp的corner case就是把dp的array变成 n+1的长度。然后最后一位赋值为1

class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s or s[0] == '0':
             return 0

        dp = [0]*(len(s)+1)
        dp[-1] = 1

        for i in range(0, len(s)):
            dp[i] = dp[i-1]
            if i >= 1:
                if s[i] == '0':
                    if int(s[i-1:i+1]) > 20 or int(s[i-1:i+1]) == 0:
                        return 0
                    else:
                        dp[i] = dp[i-2]
                elif 10 < int(s[i-1:i+1]) <= 26:
                    dp[i] += dp[i-2]

        return dp[-2]


s = Solution()
ans = s.numDecodings('7206')
print ans

P32. String to Integer (atoi)

这个答案真的是写得好。

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = re.findall('^[\+\-0]*\d+', str.strip())
        try:
            res = int(''.join(str))
            return min(max(-2**31,res), 2**31-1)
        except:
            return 0

results matching ""

    No results matching ""