[leetcode] Decode ways

http://leetcode.com/onlinejudge#question_91
Decode WaysJun 25 '121292 / 5011
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.


Solution: DP Problem again.

public class Solution {
    public int numDecodings(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s.length() == 0) return 0;
        int num[] = new int[s.length()];
        
        int n1 = Integer.parseInt(s.substring(0,1));        
        if(n1==0)  return 0;
        if(s.length() == 1) return 1;
        num[0]=1;
        
        int n2 = Integer.parseInt(s.substring(0,2));
        if(n2==10 || n2==20 || (n2>26 && n2%10!=0)) num[1] = 1;
        else if(n2<=26 && n2>=11) num[1] = 2;
        else return 0;
        
        for(int i=2;i<s.length();i++){
            n1 = Integer.parseInt(s.substring(i,i+1));
            n2 = Integer.parseInt(s.substring(i-1,i+1));
            if(n1==0 && n2==0) return 0;
            if(n1 != 0) num[i] += num[i-1];            
            if(n2>=10 && n2 <= 26) num[i] += num[i-2];
        }
        return num[s.length() -1];
    }
}

你可能感兴趣的:(Algorithm)