2015年9月20日星期日

Decode Ways

Problem:
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).
Idea:



Solution: 

public class Solution {
    public int numDecodings(String s) {
        if(s == null || s.length()<1) return 0;
     
        int store[]=new int[s.length()+1];
        store[0]=decodeable(s.substring(0,1))?1:0;
        if(s.length()<2) return store[0];
        store[1]=decodeable(s.substring(1,2))?store[0]:0;
        if(s.length()>1&&decodeable(s.substring(0,2))){
            store[1] +=1;
        }
       
        for(int i =2;i<s.length();i++){
            if(decodeable(s.substring(i,i+1))){
                store[i] = store[i-1];
            }
            if(decodeable(s.substring(i-1,i+1))){
                store[i] +=store[i-2];
            }
        }
       
        return store[s.length()-1];
       
    }
   
    public boolean decodeable(String str){
        int result = 0;
        if(str.charAt(0)=='0') return false;
        for(int i =0;i<str.length();i++){
            result =result *10+str.charAt(i)-'0';
        }
        if(result<=26 && result>0) return true;
        return false;
    }
}

没有评论: