zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):091-Decode Ways

    题目来源:

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


    题意分析:

      A-Z解码为分别1-26。给定一个解码序列,输出所有可能的个数。比如序列“12”可以代表AB和L,2种可能。


    题目思路:

      这是一个动态规划的问题。用一个数组ans记录序列的结果,其中ans[i]代表序列s[i:]有多少种可能。令tmp=int(s[i])*10 + int(s[i + 1]),如果tmp == 10 or tmp == 20,那么ans[i] =ans[i + 2];如果tmp >26,那么ans[i] = ans[i+1],否则ans[i] = ans[i+1]+ans[i+2]。


    代码(Python):

     1 class Solution(object):
     2     def numDecodings(self, s):
     3         """
     4         :type s: str
     5         :rtype: int
     6         """
     7         size = len(s)
     8         if size == 0:
     9             return 0
    10         ans = [0 for i in range(size)]
    11         i = size - 1
    12         while i >= 0:
    13             if s[i] == '0':
    14                 ans[i] = 0; i -= 1
    15                 continue
    16             if i == size - 1:
    17                 ans[i] = 1
    18             elif i == size - 2:
    19                 tmp = int(s[i]) * 10 + int(s[i+1])
    20                 if tmp ==10 or tmp == 20 or (tmp > 26 and tmp % 10 != 0):
    21                     ans[i] = 1
    22                 elif tmp % 10 == 0:
    23                     ans[i] = 0
    24                 else:
    25                     ans[i] = 2
    26             else:
    27                 tmp = int(s[i]) * 10 + int(s[i+1])
    28                 if tmp == 10 or tmp == 20:
    29                     ans[i] = ans[i + 2]
    30                 elif tmp > 26:
    31                     ans[i] = ans[i+1]
    32                 else:
    33                     ans[i] = ans[i + 1] + ans[i + 2]
    34             i -= 1
    35         return ans[0]
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/5088815.html 

  • 相关阅读:
    js计时功能
    sql缓存与WebSocket结合
    安装iis8
    WebSocket 聊天室加自制服务器
    简易web服务器
    UserControl 用户定义组件
    web.config中configSections section节 -Z
    SQL函数返回表的示例-Z
    sql with as 用法-Z
    计算机组成原理-第3章-3.1
  • 原文地址:https://www.cnblogs.com/chruny/p/5088815.html
Copyright © 2011-2022 走看看