码迷,mamicode.com
首页 > 其他好文 > 详细

Decode Ways

时间:2016-07-12 06:46:53      阅读:137      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!