2013.12.27 02:32
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.
Solution1:
This is a simple practice for dynamic programming.
Time complexity is O(n), space complexity is O(n), where n is the length of the string.
Accepted code:
1 // 1AC, very nice~ 2 class Solution { 3 public: 4 int numDecodings(string s) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 int *a; 8 int i, n; 9 10 n = s.length(); 11 if(n <= 0){ 12 return 0; 13 } 14 a = new int[n + 1]; 15 16 a[0] = 1; 17 if(s[n - 1] == '0'){ 18 a[1] = 0; 19 }else{ 20 a[1] = 1; 21 } 22 for(i = n - 2; i >= 0; --i){ 23 if(s[i] == '0'){ 24 a[n - i] = 0; 25 }else{ 26 a[n - i] = a[n - i - 1]; 27 if((s[i] - '0') * 10 + (s[i + 1] - '0') <= 26){ 28 a[n - i] += a[n - i - 2]; 29 } 30 } 31 } 32 33 n = a[n]; 34 delete[] a; 35 return n; 36 } 37 };
Solution2:
It seems an extra array is completely unnecesssary for this problem, as the recurrence relation only involves the last two states.
Some minor changes in code will reduce space complexity to O(1). Time complexity is still O(n).
Accepted code:
1 // 1WA, 1AC, make sure you write good code. 2 class Solution { 3 public: 4 int numDecodings(string s) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 int a1, a2, a3; 8 int i, n; 9 10 n = s.length(); 11 if(n <= 0){ 12 return 0; 13 } 14 15 a1 = 1; 16 if(s[n - 1] == '0'){ 17 a2 = 0; 18 }else{ 19 a2 = 1; 20 } 21 for(i = n - 2; i >= 0; --i){ 22 if(s[i] == '0'){ 23 a3 = 0; 24 }else{ 25 a3 = a2; 26 if((s[i] - '0') * 10 + (s[i + 1] - '0') <= 26){ 27 a3 += a1; 28 } 29 } 30 a1 = a2; 31 a2 = a3; 32 } 33 34 // 1WA here, 'return a2', not 'return a3' 35 return a2; 36 } 37 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)