6Companies30days

91. Decode Ways

A message containing letters from A-Z can be encoded into numbers using the following mapping:

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, “11106” can be mapped into:

Note that the grouping (1 11 06) is invalid because “06” cannot be mapped into ‘F’ since “6” is different from “06”. Given a string s containing only digits, return the number of ways to decode it. The test cases are generated so that the answer fits in a 32-bit integer.

Example

Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).

Solution

Idea

int numDecodings(string str) {

    vector <int> ways(str.size(), 0);
    int n = str.size();

    // base cases

    // number of ways to form by last digit
    if( '1' <= str[n-1] and str[n-1] <= '9' ){
        ways[n-1] = 1;
    }

    if( str.size() < 2 ) return ways[0];

    // number of ways to form by second last digit 
    if ( '1' <= str[n-2] and str[n-2] <= '9' ){
        ways[n-2] = ways[n-1];
        int i = n-2;
        if( str[i] == '1' ){
            if( str[i+1] >= '0' and str[i+1] <= '9' ){
                ways[i] += 1;
            }
        }
        if( str[i] == '2' ){
            if( str[i+1] >= '0' and str[i+1] <= '6' ){
                ways[i] += 1;
            }
        }


    }

    // iterating through the loop 
    // # ways at any ind = # ways[i+1] ( str[i] is a char ) + # ways[i+2] ( str[i]+str[i+1] is a valid combination)
    for( int i = n-3 ; i >=0 ; i--){


        if( ways[i+1] == 0 and ways[i+2] == 0  ) break;

        if( str[i] >= '1' and str[i] <= '9' ){
            ways[i] = ways[i+1];


            if( str[i] == '1' ){
                if( str[i+1] >= '0' and str[i+1] <= '9' ){
                    ways[i] += ways[i+2];
                }
            }
            if( str[i] == '2' ){
                if( str[i+1] >= '0' and str[i+1] <= '6' ){
                    ways[i] += ways[i+2];
                }
            }


        }

    }



    return ways[0];

}