博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode.com]算法题目 - Decode Ways
阅读量:6853 次
发布时间:2019-06-26

本文共 2131 字,大约阅读时间需要 7 分钟。

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.

1 class Solution {2 public:3     int numDecodings(string s) {4         // Start typing your C/C++ solution below5         // DO NOT write int main() function6         7     }8 };
答案模板

本题情况很繁琐,尝试了好久才通过测试。注意“012”这样以零开头的string,number of ways 是0。代码如下:

1 class Solution { 2 public: 3     int numDecodings(string s) { 4         // Start typing your C/C++ solution below 5         // DO NOT write int main() function 6         int len = s.length(); 7          8         if (0==len || '0'==s.at(0)) return 0; 9         10         if (1==len) return 1;11         12         if (2==len){13             int t1 = s.at(0)-'0';14             int t2 = s.at(1)-'0';15             16             t2 += t1*10;17             18             if(10 == t2 || 20 == t2)19                 return 1;20             else if(t2<=26)21                 return 2;22             else if(0==t2%10)23                 return 0;24             else25                 return 1;26         }27         28         int *record = new int[len];29         record[0]=numDecodings(s.substr(len-1,1));30         record[1]=numDecodings(s.substr(len-2,2));31         32         for(int k=2;k
2)39 record[k]= record[k-1];40 else if (1==a)41 record[k]= record[k-1]+record[k-2];42 else // (2==a)43 {44 int kk = s_string.at(1)-'0';45 if(kk>6)46 record[k]= record[k-1];47 else48 record[k]= record[k-1]+record[k-2];49 }50 }51 int result = record[len-1];52 delete[] record;53 return result;54 55 }56 };
我的答案

注意分析其中的每一种情况,必须要都考虑周全。用record数组记录已经计算过的数据,避免用递归所产生的重复计算。

转载于:https://www.cnblogs.com/xuning/p/3311406.html

你可能感兴趣的文章
GIL(全局解释器锁)与互斥锁
查看>>
我的友情链接
查看>>
Git常用操作及分支
查看>>
关于一种求最大公约数的算法的分析与证明
查看>>
微信授权莫名创建用户数据失败的原因
查看>>
网络高手修身
查看>>
JavaWeb综合案例-键盘模拟
查看>>
Android Day03-SQLite数据库操作及ListView详解
查看>>
Looking for APAC Operations IT XML Database Developer in Shenzhen and Hongkong
查看>>
Myeclipse常用快捷键
查看>>
我的友情链接
查看>>
Unity3d多线程
查看>>
炉石传说 C# 开发笔记 (源代码整理公开)
查看>>
前端文摘:Web 开发模式演变历史和趋势
查看>>
最大子数组和问题的解
查看>>
cout设置输出数据不显示科学计数法
查看>>
zoj 1659 Mobile Phone Coverage(矩形面积并)
查看>>
python学习 day3
查看>>
Centos 6.4下用Squid配置反向代理多个内网WEB服务器
查看>>
王者荣耀之父姚晓光“奇葩”的工作理念
查看>>