面试题43:计算多少种译码方式(decode-ways)
2017-06-09 10:20
731 查看
这道题是非常典型的DP问题。按照DP的套路,关键是讨论出递推表达式,遍历过程中针对当前字符是否为'0'以及前一个字符为'0',分类讨论得出到目前字符为止最多有多少种译码方式?理清了递推表达式,代码是很简单的。
A message containing letters fromA-Zis being encoded to numbers using the following mapping:
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
A message containing letters fromA-Zis 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
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 int n = s.length(); 5 vector<int> dp(n + 1, 0); 6 7 if (n == 0 || s[0] == '0') return 0; 8 9 dp[0] = 1; 10 dp[1] = 1; 11 for (int i = 2; i <= n; i++) { 12 if (s[i-1] == '0' && s[i - 2] == '0') 13 return 0; 14 else if (s[i-2] == '0') { 15 dp[i] = dp[i - 1]; 16 }else if(s[i-1] == '0'){ 17 if(s[i-2] > '2') return 0; 18 dp[i] = dp[i-2]; 19 }else { 20 dp[i] = dp[i - 1]; 21 if (stoi(s.substr(i - 2, 2)) <= 26) { 22 dp[i] += dp[i - 2]; 23 } 24 } 25 26 } 27 return dp ; 28 } 29 };
相关文章推荐
- 一道百度面试题---200元的组合方式有多少
- 、输入某人出生日期(以字符串方式输入,如1987-4-1)使用DateTime和TimeSpan类,(1)计算其人的年龄;(2)计算从现在到其60周岁期间,总共多少天。
- [面试题].net页面间传递数值的方式有哪些?不看答案前你想到有多少呢
- js面试题:网页中实现一个计算还剩多少时间的倒数计时程序
- n对括号可以有多少种匹配排列方式(算法面试题)
- Decode Ways 编码的方式
- 李洪强IOS经典面试题 33-计算有多少个岛屿
- 、输入某人出生日期(以字符串方式输入,如1987-4-1)使用DateTime和TimeSpan类,(1)计算其人的年龄;(2)计算从现在到其60周岁期间,总共多少天。
- 面试题:计算0到n的数中有多少个2
- lua计算时间差 按照日历方式来计算时间差 而不是固定每个月都是多少天来计算
- CODE 43: Decode Ways
- A、B两伙马贼意外地在一片沙漠中发现了一处金矿,双方都想独占金矿,但各自的实力都不足以吞下对方,经过谈判后,双方同意用一个公平的方式来处理这片金矿。处理的规则如下:他们把整个金矿分成n段,由A、B开始轮流从最左端或最右端占据一段,直到分完为止。 马贼A想提前知道他们能分到多少金子,因此请你帮忙计算他们最后各自拥有多少金子?(两伙马贼均会采取对己方有利的策略)
- 面试题:以最快的速度计算一个字节(byte)里有多少bit被置1
- 常见面试题——计算一个字节里有多少bit置1
- 每天一道LeetCode-----将数字集转成字母集,计算有多少种转换方式
- 面试题 一个人射箭,每次分数在0至10之间,已知射箭10次,得分是50分,编程计算总共有多少种可能?
- 毕业论文设计客户订单界面及代码(WinForm之间传递参数,公式的Sql计算方式)
- 排列字母ILLINOIS,字母NOS,共有多少种排列方式?
- 根据年月计算每个月有多少天和返回日期是星期几
- 一段js小代码,计算距春节还有多少天