zoukankan      html  css  js  c++  java
  • Leetcode练习(python):字符串类:第91题:解码方法:一条包含字母 A-Z 的消息通过以下方式进行了编码: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。

    题目:
    解码方法:一条包含字母 A-Z 的消息通过以下方式进行了编码:  'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请计算解码方法的总数。  
    思路:
    一开始理解错题目了,使用字典去对应,发现题目要求不是这样的。
    之后使用动态规划来做,需要考虑的情况比较多,踩了很多坑。
    程序:
    class Solution:
        def numDecodings(self, s: str) -> int:
            if not s:
                return 0
            if s[0] == '0':
                return 0
            length = len(s)
            counter = 1
            auxiliary_counter = 1
            if int(s) <= 10:
                return 1
            elif 10 < int(s) <= 26:
                if int(s) == 20:
                    return 1
                else:
                    return 2
            else:
                for index in range(1, length):
                    if s[index] == '0':
                        if s[index - 1] == '1' or s[index - 1] == '2':
                            counter = auxiliary_counter
                        else:
                            return 0
                    else:
                        if s[index - 1] == '1'  or (s[index - 1] == '2' and '1' <= s[index] <= '6'):
                            auxiliary = counter
                            counter += auxiliary_counter
                            auxiliary_counter = auxiliary
                        else:
                            auxiliary_counter = counter
            return counter
  • 相关阅读:
    HIDS逐渐的成为主流 java程序员
    怎样做反向域名解析(反向DNS解析)? java程序员
    入侵检测系统的性能的辨别(2) java程序员
    Codeforces Round #146 (Div. 2)
    usaco1.34Prime Cryptarithm
    poj3667 hotel(线段树区间合并)
    poj1330Nearest Common Ancestors(水LCA)
    hdu4135Coprime(容斥原理)
    hdu1541Stars(树状数组)
    usaco 1.43Arithmetic Progressions
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12844514.html
Copyright © 2011-2022 走看看