91 Decode Ways

https://leetcode.com/problems/decode-ways/#/description

A message containing letters fromA-Zis 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.

分析及代码

public int numDecodings(String s) {
    int len = s.length();
    if(len == 0) {
        return 0;
    }
    int[] path = new int[len + 1];
    path[0] = 1;
    path[1] = s.charAt(0) == '0'? 0: 1;
    for(int i = 2; i <= len; i++) {
        char pre = s.charAt(i - 2);
        char cur = s.charAt(i - 1);
        if (cur == '0') {
            if(pre != '1' && pre != '2') {
                path[i] = 0;
            } else {
                path[i] = path[i - 2];
            }
        } else if (pre == '1' || (pre == '2' && cur >= '0' && cur <= '6')) {
            path[i] = path[i - 1] + path[i - 2];
        } else {
            path[i] = path[i - 1];
        }
    }
    return path[len];
}

results matching ""

    No results matching ""