Monday, November 25, 2013

LeetCode Problem : Decode Ways

Problem


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.

Code

int combine(char c1,char c2)
{
    if(c1 == '2' && c2 < '7')
        return 1;
    if(c1 == '1')
        return 1;
    return 0;
}
int alone(char c1)
{
    if(c1 != '0')
        return 1;
    return 0;
}
int numDecodings(string s) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    int n = s.size();
    if(n == 0)
    return 0;
    vector<int> M(n,0);
    M[0] = alone(s[0]);
    if(n == 1)
        return M[0];
    int first = alone(s[1]);
    if(first > 0)
        M[1] = M[0];
    M[1] += combine(s[0],s[1]);
    for(int i = 2;i < n; ++i){
        int ways = 0;
        int single = alone(s[i]);
        int both = combine(s[i - 1],s[i]);
        if(single > 0)
            ways += M[i - 1];
        if(both > 0)
            ways += M[i - 2];
        M[i] = ways;
    }
    return M[n - 1];
}

No comments:

Post a Comment