Leetcode#91 Decode Ways

原题地址

动态规划题,注意0导致的小陷阱。

代码:

 1 int numDecodings(string s) {
 2         if (s.empty() || s[0] < '1' || s[0] > '9') return 0;
 3         
 4         int sum = s[s.length() - 1] >= '1' && s[s.length() - 1] <= '9' ? 1 : 0;
 5         int nextnext = 1;
 6         int next = sum;
 7         
 8         for (int i = s.length() - 2; i >= 0; i--) {
 9             if (s[i] >= '0' && s[i] <= '9') {
10                 if (s[i] == '1' || (s[i] == '2' && s[i + 1] >= '0' && s[i + 1] <= '6'))
11                     sum = next + nextnext;
12                 else if (s[i] == '0')
13                     sum = 0;
14                 else
15                     sum = next;
16                 nextnext = next;
17                 next = sum;
18             }
19             else
20                 return 0;
21         }
22         
23         return sum;
24 }
原文地址:https://www.cnblogs.com/boring09/p/4259364.html