首页 > 其他 > 详细

Decode Ways

时间:2016-07-12 06:44:28      阅读:272      评论:0      收藏:0      [点我收藏+]

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.

Example

Given encoded message 12, it could be decoded as AB (1 2) or L (12).
The number of ways decoding 12 is 2.

分析:

用total[i]表示从i 到 string.length() - 1总共的解法。 我们可以从最后一个数字开始,最后一个数字如果在1-9之间,只有一种decode way, total[length - 1] = 1. 对于倒数第二个数字呢,如果倒数第二个数字不是0,很明显,我们至少有total[i] = total[i + 1], 如果俩个数字合在一起可以组成一个valid number, 那么total[i] += total[i + 2].

 1 public class Solution {
 2     /**
 3      * @param s a string,  encoded message
 4      * @return an integer, the number of ways decoding
 5      */
 6     public int numDecodings(String s) {
 7         if (s == null || s.length() < 1) return 0;
 8         int[] total = new int[s.length()];
 9 
10         for (int i = s.length() - 1; i >= 0; i--) {
11             char c = s.charAt(i);
12             if (c >= 1 && c <= 9) {
13                 if(i == s.length() - 1) {
14                     total[i] = 1;
15                 } else {
16                     total[i] = total[i + 1];
17                     String strNumber = s.substring(i, i + 2);
18                     int number = Integer.parseInt(strNumber);
19                     if (number <= 26) {
20                         if (i + 2 == total.length) {
21                             total[i] += 1;
22                         } else {
23                             total[i] += total[i + 2];
24                         }
25                     }
26                 }
27             }
28         }
29         return total[0];
30     }
31 }

 

Decode Ways

原文:http://www.cnblogs.com/beiyeqingteng/p/5662201.html

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