[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数组记录已经计算过的数据,避免用递归所产生的重复计算。
分类:
算法题目
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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)