Decode Ways

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.

For 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         int len = s.length();
 4         if(len<=0) return 0;
 5         if(len==1) return check1(s.charAt(0));
 6         if(len>=1 && s.charAt(0)=='0') return 0;
 7         int f2= 1,f1=0,fn=0;
 8         f1 = check1(s.charAt(0))*check1(s.charAt(1))+ check2(s.charAt(0),s.charAt(1));
 9         for(int i=2;i<len;i++){
10             if(check1(s.charAt(i))==1) fn = f1;
11             if(check2(s.charAt(i-1),s.charAt(i))==1) fn+=f2;
12             f2 = f1;
13             f1 = fn;
14             fn=0;
15         }
16         return f1;
17     }
18     public int check1 (char a){
19         return a=='0'?0:1;
20     }
21     public int check2 (char a,char b){
22         if(a=='1'||(a=='2'&&b<='6')) return 1;
23         else return 0;
24     }
25 }
View Code

 

posted @ 2014-02-06 15:14  krunning  阅读(106)  评论(0编辑  收藏  举报