[leetcode.com]算法题目 - Decode Ways

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 below
5         // DO NOT write int main() function
6         
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             else
25                 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<len;k++){
33             string s_string = s.substr(len-k-1,k+1);
34             
35             int a = s_string.at(0)-'0';
36             if (0==a)
37                 record[k]=0;
38             else if (a>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                 else
48                     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数组记录已经计算过的数据,避免用递归所产生的重复计算。

posted on   Horstxu  阅读(212)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示