****(leetcode_string) Decode Ways
来源:互联网 发布:网络手机铃声大全试听 编辑:程序博客网 时间:2024/06/06 07:36
Decode Ways
Total Accepted: 24925 Total Submissions: 153233My SubmissionsA 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.
Have you met this question in a real interview?
Yes
No
Discuss
1、回溯法,超时。。。。
class Solution { int ret; void dfs(string s, int curDep, int maxDep){ if(curDep==maxDep){ ret++; return; } if(s[curDep]=='0') return; dfs(s,curDep+1,maxDep); if(curDep+1<maxDep){ int tmp = (s[curDep]-'0')*10+(s[curDep+1]-'0'); if(tmp>=10&&tmp<27) dfs(s,curDep+2,maxDep); } }public: int numDecodings(string s) { if(s=="") return 0; dfs(s,0,s.length()); return ret; }};
2、动态规划思路:
当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件:
1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。
2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。
所以用r1表示n-1长度的字符串表示的数目, r2表示n-2长度的字符串表示的数目
class Solution { public: int numDecodings(string s) { if(s==""||s[0]=='0') return 0; int r1=1,r2=1; for(int i=1;i<s.length();i++){ if(s[i]=='0') r1=0; if(s[i-1]=='1'||(s[i-1]=='2'&&s[i]<='6')){ r1=r1+r2; r2=r1-r2; } else r2=r1; } return r1; }};
0 0
- ****(leetcode_string) 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
- 深入了解javascript中的exec与match方法
- java静态变量和静态方法的集成
- 李敏:手机淘宝的架构演化实践
- Object-c的三大特性 学习笔记
- [C++]LeetCode: 61 Search a 2D Matrix
- ****(leetcode_string) Decode Ways
- 7zip命令行使用详细手册
- 《LoadRunner 没有告诉你的》之四——理解性能
- the x32 ODBC driver for eXtremeDB
- Ubuntu安装JDK
- Memcache内存分配策略
- 《LoadRunner 没有告诉你的》之五——无所不在的性能测试 (已完稿)
- Java内存访问重排序的研究
- EasyUi+MVC+WCF 删除信息--考试系统