LintCode 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 encoded message 12, it could be decoded as AB (1 2) or L (12).
The number of ways decoding 12 is 2.

Given an encoded message containing digits, determine the total number of ways to decode it.

public class Solution {
    /**
     * @param s a string,  encoded message
     * @return an integer, the number of ways decoding
     */
   public int numDecodings(String s) {
        if(null == s || s.length() <= 0)
            return 0;
        
        if(s.length() == 1 && s.charAt(0) == '0')
            return 0;
        
        int[] numDecodings = new int[s.length() + 1];
        numDecodings[0] = 1;
        for(int i = 1;i <= s.length();i++)
        {
            if(s.charAt(i - 1) == '0')
            {
                if(i- 2 >= 0)
                {
                    // 如果出现类似"50"这样的数字直接返回0
                    if(s.charAt(i - 2) != '1' && s.charAt(i - 2) != '2')
                    {
                        return 0;
                    }
                    else
                    {
                        numDecodings[i] += numDecodings[i - 2];
                        continue;
                    }
                }
            }
            numDecodings[i] += numDecodings[i - 1];
            if(i - 2 >= 0)
            {
                if((s.charAt(i - 2) == '1') || (s.charAt(i - 2) == '2' 
                        && s.charAt(i - 1) >= '1' && s.charAt(i - 1) <= '6'))
                {
                    numDecodings[i] += numDecodings[i - 2];
                }
            }
        }
        return numDecodings[s.length()];
    }
}

你可能感兴趣的:(LintCode Decode Ways)