Notes:

1. Use long since it will overflow.

2 When c != '*', it is normal decode ways. Thus current ways is c could be single digits (c > 0 ?) * prev or c combine with '1' (any digits) or c combine with '2' (only c <= 6).

3. When c == '*', it could be single digit 9 * prev  or combine with '1' 9 * e1 or combine with '2' 6 * e2. In this case, c could be '1' or '2' for next round so e1 = e0, e2 = e0

 

 

class Solution {
    public int numDecodings(String s) {
        int mod = (int) (Math.pow(10, 9) + 7);
        long[] elements = new long[3];
        elements[0] = 1;
        for (char c : s.toCharArray()) {
            long prev = elements[0];
            if (c == '*') {
                elements[0] = 9 * prev + 9 * elements[1] + 6 * elements[2];
                elements[1] = prev;
                elements[2] = prev;
            } else {
                elements[0] = (c > '0' ? 1 : 0) * prev + elements[1] + (c <= '6' ? 1 : 0) * elements[2];
                elements[1] = (c == '1' ? 1 : 0) * prev;
                elements[2] = (c == '2' ? 1 : 0) * prev;
            }
            elements[0] %= mod;
        }
        return (int) elements[0];
    }
}

 

posted on 2017-09-04 16:36  keepshuatishuati  阅读(152)  评论(0)    收藏  举报