Decode Ways
来源:互联网 发布:淘宝标题栏素材 编辑:程序博客网 时间:2024/05/29 03:50
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[i]为前i个数的译码方法,s[len]为字符串。
首先当len=0或者s[0]=0时,是不存在译码方法的;
dp[0]=0,
dp[i]=s[i-1]单独作为一个字母的译码方法+s[i-1]和s[i-2]一起作为一个字母的译码方法,1<=i<=len.
具体代码为:
class Solution {public: int numDecodings(string s) { int len=s.size(); int i,j,result; int *dp=new int[len+1]; if(len==0||s[0]=='0') return 0; dp[0]=1; for(i=1;i<=len;i++){ if(s[i-1]=='0') dp[i]=0; else dp[i]=dp[i-1]; if(i>1&&(s[i-2]=='1'||(s[i-2]=='2'&&s[i-1]<='6'))) dp[i]+=dp[i-2]; } result=dp[len]; delete []dp; return result; }};
阅读全文
0 0
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode ways
- Decode Ways
- Decode Ways
- Decode Ways
- Decode Ways
- linux安装jdk
- 计算广告学习笔记3.1 受众定向-受众定向概念
- 深入理解Http协议
- (OK) Android-x86-7.1.1
- php_建站你用什么工具?
- Decode Ways
- 手动删除脱机域信息(适用于重装域后使用原计算机名)
- 四轴飞行器姿态算法
- 微信小程序如何动态增删class类名
- 伪数据科学家_VS_真数据科学家
- 基于canvas的图片反色处理
- Nginx+Tomcat+Redis负载均衡Session共享实现超级简单(CentOS6.9系统 Java版本)
- JEESZ分布式架构1--CentOs下安装jdk7(环境准备)
- 抓日志命令