《leetCode》:Decode Ways
2015-12-26 21:22
429 查看
题目
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.
思路和以前做的爬楼梯的题目类似;只是多了一些限制条件。实现代码如下:
/* 思路,采用动态规划的方法。 例如,当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件: 1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。 2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。 */ int char2num(char ch){ return ch-'0'; } int numDecodings(char* s) { if(s==NULL||strlen(s)<=0){ return 0; } int len=strlen(s); if(len==1){ return (s[0]!='0')?1:0; } else if(len==2){//求出字符长度为2的译码方法。 return ((s[0]!='0'&&s[1]!='0')?1:0)+((s[0]!='0'&&(char2num(s[0])*10+char2num(s[1])<=26))?1:0); } //用来保存结果 int *res=(int *)malloc(len*sizeof(int)); if(res==NULL){ exit(EXIT_FAILURE); } memset(res,0,len*sizeof(int)); res[0]= (s[0]!='0')?1:0; res[1]=((s[0]!='0'&&s[1]!='0')?1:0)+((s[0]!='0'&&(char2num(s[0])*10+char2num(s[1])<=26))?1:0); for(int i=2;i<len;i++){ if(s[i]!='0'){//1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。 res[i]+=res[i-1]; } //2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。 if(s[i-1]!='0'&&char2num(s[i-1])*10+char2num(s[i])<=26){// res[i]+=res[i-2]; } } return res[len-1]; }
相关文章推荐
- HBuilder手机退出APP的方式
- online_judge_1150
- MSYS2镜像源
- 使eclipse支持lombok.jar
- C 入门 第十一节
- JDBC学习笔记(2)
- php+xmapp中文乱码
- Visual studio 2015 C++ 中嵌入python文件的环境搭建
- 变量子串的常用操作
- Cocos2D游戏项目CCTableView在Xcode7.2下的无法滚动问题
- Cocos2D游戏项目CCTableView在Xcode7.2下的无法滚动问题
- shiro异常
- Amaze UI定制
- Cocos2D游戏项目CCTableView在Xcode7.2下的无法滚动问题
- TK1搭建live555
- 7 Managing Users and Securing the Database
- mysql+python3
- HTML5(一)HTML5表单类型与属性
- InputMethodManagerService 学习摘要
- Android 新support库大集结