[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 2013-09-10 00:00  Horstxu  阅读(209)  评论(0编辑  收藏  举报

导航