Wednesday, December 24, 2014

Decode Ways

Q:
A message containing letters from A-Z is 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.

T:
DP. The number of ways of the sub string that ends at i depends on the ways of the sub string ending at i-1 and i-2.

A:

class Solution {
public:
    bool check(char a) {
        if(a == '0') {
            return false;
        } else {
            return true;
        }
    }
    bool check(char a, char b) {
        if(a == '1' || (a == '2' && b <= '6')) {
            return true;
        }
        return false;
    }
    int numDecodings(string s) {
        int n = s.size();
        if(n == 0) {
            return 0;
        }
        if(n == 1) {
            if(check(s[0])) {
                return 1;
            }
            return 0;
        }
        int c = 0;
        int c2 = check(s[0]);
        int c1 = 0;
        if(check(s[0]) && check(s[1])) {
            c1++;
        }
        if(check(s[0], s[1])) {
            c1++;
        }
        for(int i=2; i < n; i++) {
            if(check(s[i])) {
                c += c1;
            }
            if(check(s[i-1], s[i])) {
                c += c2;
            }
            if (c == 0) {
                return 0;
            }
            c2 = c1;
            c1 = c;
            c = 0;
        }
        return c1;
    }
};

No comments:

Post a Comment