Decode ways--LeetCode
来源:互联网 发布:mac user文件夹在哪 编辑:程序博客网 时间:2024/05/29 09:46
题目:
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问题,首先定义一个数组,dp[i]为到第i个字符所能组成的所有编码方式的个数。那么对于dp[i+1]来说,肯定至少和dp[i]一样多,如果第i个字符和i+1个字可以合成一个字符,那么dp[i+1] += dp[i-1]。不过这里需要注意的是违规字符。
#include <iostream>#include <string>#include <vector>using namespace std; int Decode_num(string& str){vector<int> vec(str.size(),0);if(str.size() <2)return 1;vec[0] =1;if(str[0]=='1' || str[1]<='6')vec[1] =2;int i;int tmp;for(i=2;i<str.size();i++){if(str[i] != '0') //注意这里需要判断字符串是否为违法字符串vec[i] = vec[i-1];tmp = str[i-1]-'0';tmp = tmp*10 + str[i]-'0'; if(str[i-1]!='0' && tmp <=26) //需要注意判断是够为非法字符串vec[i] += vec[i-2];} return vec[str.size()-1];} int main(){string str("1231725251414392431271");//string str("1235533426");//string str("1224");cout<<Decode_num(str)<<endl;cout<<numDecodings(str)<<endl;return 0;}
1 0
- Leetcode 91. Decode Ways&&639.Decode ways
- LeetCode: Decode Ways
- [LeetCode]Decode Ways
- LeetCode Decode Ways
- LeetCode : Decode Ways
- [Leetcode] Decode Ways *
- [leetcode] Decode Ways (!!)
- leetcode 17: Decode Ways
- Leetcode: Decode ways
- LeetCode Decode Ways
- [LeetCode]Decode Ways
- [leetcode] Decode Ways
- Leetcode: Decode Ways
- [LeetCode] Decode Ways
- [leetcode]Decode Ways
- LeetCode-Decode Ways
- [leetcode] Decode Ways
- [LeetCode] Decode Ways
- 阴影映射(Shadow Map)的研究(一)
- 直接链接字段的添加以及substring内存泄露的考虑
- activity生命周期
- 基于java反射知识的类查看器
- Hibernate缓存机制
- Decode ways--LeetCode
- 让Dev C++支持C++11
- JSP知识点
- 用c语言实现 编写一个函数reverse_string(char * string)
- HR问的问题
- 正则表达式知识整理
- 借用gcc源码中的sha1.c进行SHA1计算
- ng-repeat
- 迅雷2014C++研发笔试卷C