LeetCode 091: Decode Ways
2016-06-03 13:48
369 查看
091. Decode Ways
Difficulty: MediumA 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.
思路
类似斐波那契数列,以“12304”的解码为例,用以下表达式表示解码可得到的不同结果数:f(“12304”) = f(“1230”)g(“4”) + f(“123”)g(“04”);
f(“1230”) = f(“123”)g(“0”) + f(“12”)g(“30”)。
g(s)判断s是否可以解码得到单个字母,返回结果只有1和0,如g(“1”)=1,g(“27”)=0。
此外需要注意“0”和“04”都不可解码,即只要‘0’为字符串的第一个字符,该字符串不可解码,g(“0.*”) = 0。
用循环比递归更高效,减少重复运算。
代码
[C++]class Solution { public: int numDecodings(string s) { if (s.size() <= 0) return 0; int numOne, numTwo; numOne = numTwo = 1; int Final = 0; for (int i = 0; i < s.size(); ++i) { if (s[i] == '0') numTwo = 0; Final = numTwo; if (IsEncoded(s, i)) Final += numOne; numOne = numTwo; numTwo = Final; } return Final; } bool IsEncoded(const string &s, int index) { if (index < s.size() && index > 0) { string temp(s, index - 1, 2); int num = stoi(temp, NULL); if (num > 9 && num <= 26) return true; } return false; } };
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性