博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 91 Decode Ways
阅读量:4170 次
发布时间:2019-05-26

本文共 1694 字,大约阅读时间需要 5 分钟。

题目描述:
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

分析:采用动态规划方法,定义一个数组dp,大小为:数组大小+1,令dp[0]=1,其他的数组元素初值设为0,dp[i]表示数字字符串的前i位(包含第i位)有多少种解码方案。

遍历数字字符串s,
如果当前位s[i]不为0,并且当前位可以和前面1位能够组成闭区间 [11,26] 之间的某个数(即:当前位和其前一位是某个字母的编码),那么dp[i+1]=dp[i]+dp[i-1];
如果当前位s[i]不为0,并且当前位和其前面的一位构成的数字不在区间[11,26]内(即:当前位和其前一位不是某个字母的编码),那么dp[i+1]=dp[i];
如果当前位s[i]为0,则其前一位一定存在并且一定是1或2(因为该数字字符串是某一字母串的编码,而只有10和20是字母的编码),又因为单独一个0不是任何字母的编码,那么在这种情况下,dp[i+1]=dp[i-1]
【第一位肯定不能为0,也不能有连续的0
像10,20这种,有dp[i] = dp[i-2]
00,30,40...等都是非法的。。。。】

python代码1:

class Solution(object):    def numDecodings(self, s):        """        :type s: str        :rtype: int        """        if len(s)==0:            return 0        dp=[1]+[0]*len(s)        bool_ok=lambda x:x[0]!='0' and int(x)>=1 and int(x)<=26        for i in range(1,len(s)+1):            dp[i]=dp[i-1] if bool_ok(s[i-1:i]) else 0            if i>=2:                dp[i]=dp[i]+(dp[i-2] if bool_ok(s[i-2:i]) else 0)        return dp[len(s)]
python代码2:

class Solution(object):    def numDecodings(self, s):        """        :type s: str        :rtype: int        """        if s=='':            return 0        dp=[1]+[0]*len(s)        bool_ok=lambda x:x[0]!='0' and int(x)>=1 and int(x)<=26        for i in range(len(s)):            dp[i+1]=dp[i] if bool_ok(s[i:i+1]) else 0            if i>=1:                dp[i+1]+=dp[i-1] if bool_ok(s[i-1:i+1]) else 0        return dp[len(s)]

转载地址:http://wcyai.baihongyu.com/

你可能感兴趣的文章
“VM6辅助启动.bat”生成器.hta
查看>>
windows脚本调试howto
查看>>
五笔86版字根图程序
查看>>
Oracle EBS R12 - Use Rman to Clone Oracle EBS R12.1.1 without shutting down source Database and MT
查看>>
Oracle EBS - What happening when executing adpreclone.pl in DB and Apps Tier?
查看>>
Oracle EBS - What happening when executing adcfgclone.pl in DB Tier as well as Apps Tier?
查看>>
Oracle EBS - Details of Adpreclone and Adcfgclone
查看>>
两个对Oracle性能影响很大的io参数
查看>>
Win32ASM备忘之搭建UltraEdit实验环境
查看>>
The Best Linux Distribution of them all
查看>>
Oracle Apps DBA Interview Questions
查看>>
简单屏幕锁(Simple Screen Locker) 1.1.6.16
查看>>
Bash String Manipulation Examples – Length, Substring, Find and Replace
查看>>
String Operations in Shell
查看>>
烦请解释一下“驱动表”的概念
查看>>
IPAide(IP助手) v1.01
查看>>
Oracle 11g RAC SCAN basics
查看>>
ASM appears to be running, but connect via sqlplus, says idle instance.??
查看>>
Oracle EBS R12 - Steps and Issues/Resolutions during R12.1.1 to R12.1.3 Upgration
查看>>
HW的最后一轮面试
查看>>