Decode Ways
来源:互联网 发布:北京信索咨询集团知乎 编辑:程序博客网 时间:2024/05/16 14:42
题目:
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.
分析:可以用贪心的思想,而且当前数字只与前面的数字有关。
代码如下:
int numDecodings(string s) {
int n=s.size();
if(n==0)return 0;
int *result=new int[n+1];
memset(result,0,(n+1)*sizeof(int));
result[0]=1;
for(int i=1;i<=n;i++)
{
if(s[i-1]!='0')
{
result[i]+=result[i-1];
}
if(i>=2&&s[i-1]-'0'+10*(s[i-2]-'0')<=26&&s[i-1]-'0'+10*(s[i-2]-'0')>=10)
{
result[i]+=result[i-2];
}
}
return result[n];
}
- 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 标准目录结构
- 业务对象销售订单
- 用php实现备份数据库ZIP及导出
- QML 基础类型 vector 和 matrix
- Decode Ways
- 开源C/C++网络库比较
- MyEclipse搭建SSH框架 Struts2.1+Spring3.0+hibernate3.3
- java字符串转数字
- 网页中实现"分享至微博、QQ空间等"代码示例
- 赵雅智:拨打电话操作
- 自己编写克隆函数
- Spring集成Activiti配置
- 解决microsoft sql server error:15138的方法