首页 > 其他 > 详细

Leetcode#91 Decode Ways

时间:2015-01-29 14:00:23      阅读:231      评论:0      收藏:0      [点我收藏+]

原题地址

 

动态规划题,注意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 }

 

Leetcode#91 Decode Ways

原文:http://www.cnblogs.com/boring09/p/4259364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!