首页 > 代码库 > [LeetCode]91 Decode Ways

[LeetCode]91 Decode Ways

https://oj.leetcode.com/problems/decode-ways/

http://blog.csdn.net/linhuanmars/article/details/24570759

public class Solution {
    public int numDecodings(String s)
    {
        if (s == null || s.length() == 0)
            return 0;   // invalid input
            
        char[] chars = s.toCharArray();
        
        if (chars[0] == ‘0‘)
            return 0;
        
        int[] ways = new int[chars.length];
        ways[0] = 1;
        
        for (int i = 1 ; i < chars.length ; i ++)
        {
            char c = chars[i];
            char lastc = chars[i - 1];
            
            if (c == ‘0‘)
            {
                if (lastc == ‘1‘ || lastc == ‘2‘)
                {
                    if (i == 1)
                        ways[i] = 1;
                    else
                        ways[i] = ways[i - 2];
                }
                else
                    return 0;
            }
            else // not 0
            {
                if (lastc == ‘0‘ || lastc > ‘2‘)    // Cannot 2 char
                    ways[i] = ways[i - 1];
                else if (lastc == ‘2‘ && c > ‘6‘ && c <=‘9‘)
                    ways[i] = ways[i - 1];
                else if (i == 1)
                    ways[i] = 2;
                else
                    ways[i] = ways[i - 1] + ways[i - 2];
            }
        }
        
        return ways[chars.length - 1];
    }
}


[LeetCode]91 Decode Ways