1. 程式人生 > >[LintCode] Decode Ways

[LintCode] Decode Ways

ron ane con eterm number panel pre str using

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.

 1 public class Solution {
 2     public int numDecodings(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6         return dfs(s, s.length() - 1);   
 7     }
 8     private int dfs(String s, int end){
 9         //
base case of length 1 10 if(end == 0){ 11 if(s.charAt(end) != ‘0‘){ 12 return 1; 13 } 14 else{ 15 return 0; 16 } 17 } 18 //base case of length 2 19 if(end == 1){ 20 int ways = 0; 21 if
(s.charAt(end - 1) == ‘0‘){ 22 return 0; 23 } 24 if(s.charAt(end) != ‘0‘){ 25 ways++; 26 } 27 int num = (s.charAt(end - 1) - ‘0‘) * 10 + (s.charAt(end) - ‘0‘); 28 if(num <= 26){ 29 ways++; 30 } 31 return ways; 32 } 33 int ways = 0; 34 if(s.charAt(end) != ‘0‘){ 35 ways += dfs(s, end - 1); 36 } 37 int num = (s.charAt(end - 1) - ‘0‘) * 10 + (s.charAt(end) - ‘0‘); 38 if(s.charAt(end - 1) != ‘0‘ && num <= 26){ 39 ways += dfs(s, end - 2); 40 } 41 return ways; 42 } 43 }

 1 public class Solution {
 2     public int numDecodings(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6         int n = s.length();
 7         int[] states = new int[n + 1];
 8         states[0] = 1;
 9         states[1] = (s.charAt(0) == ‘0‘ ? 0 : 1);
10         for(int i = 2; i <= n; i++){
11             states[i] = 0;
12         }
13         for(int i = 2; i <= n; i++){
14             int num = (s.charAt(i - 2) - ‘0‘) * 10 + (s.charAt(i - 1) - ‘0‘);
15             if(s.charAt(i - 1) != ‘0‘){
16                 states[i] += states[i - 1];
17             }
18             if(s.charAt(i - 2) != ‘0‘ && num <= 26){
19                 states[i] += states[i - 2];
20             }
21             if(states[i] == 0){
22                 return 0;
23             }
24         }
25         return states[n];
26     }
27 }

[LintCode] Decode Ways