GuilinDev

Lc0639

05 August 2008

639 Decode Ways II

跟91比多了个星号*,可以作为任意单个数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
    /*
    https://leetcode.com/problems/decode-ways-ii/discuss/105275/Java-DP-O(n)-time-and-O(1)-space
    DP, O(n) time and O(1) space
    */
    public int numDecodings(String s) {
        long[] res = new long[2];
        res[0] = ways(s.charAt(0));
        if (s.length() < 2) {
            return (int)res[0];
        }
        
        res[1] = res[0] * ways(s.charAt(1)) + ways(s.charAt(0), s.charAt(1));
        for (int j = 2; j < s.length(); j++) {
            long temp = res[1];
            res[1] = (res[1] * ways(s.charAt(j)) + res[0] * ways(s.charAt(j-1), s.charAt(j))) % 1000000007;
            res[0] = temp;
        }
        return (int)res[1];
    }
    
    private static int ways(int ch) {
        if (ch == '*') {
            return 9;
        }
        if (ch == '0') {
            return 0;
        }
        return 1;
    }
    
    private static int ways(char ch1, char ch2) {
        String str = "" + ch1 + "" + ch2;
        if (ch1 != '*' && ch2 != '*') {
            if (Integer.parseInt(str) >= 10 && Integer.parseInt(str) <= 26) {
                return 1;
            }
        } else if (ch1 == '*' && ch2 == '*') {
            return 15;
        } else if (ch1 == '*') {
            if (Integer.parseInt("" + ch2) >= 0 && Integer.parseInt("" + ch2) <= 6) {
                return 2;
            } else {
                return 1;
            }
        } else {
            if (Integer.parseInt("" + ch1) == 1) {
                return 9;
            } else if (Integer.parseInt("" + ch1) == 2) {
                return 6;
            }
        }
        return 0;
    }
}