91 Decode Ways

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.

Solution

class Solution {
public:
    int numDecodings(string s) {
        int n = s.size();
        if ( n == 0 ) return 0;
        if ( n == 1 and s[0] != '0' ) return s[0] != '0';
        vector<int> numWays(n, 0);
        numWays[0] = ( s[0] != '0' );
        if ( s[1] != '0' ) numWays[1] += numWays[0];
        if ( s[0] != '0' and atoi(s.substr(0, 2).c_str()) <= 26 ) numWays[1] += 1;
        for ( int i = 2; i <= n-1; i++ ) {
            if ( s[i] != '0' ) numWays[i] += numWays[i-1];
            if ( s[i-1] != '0' and atoi(s.substr(i-1, 2).c_str()) <= 26 ) numWays[i] += numWays[i-2];
        }
        return numWays[n-1];
    }
};

Notes
DP solution:
When adding s[i] to s[0:i], devide the problem into two sub-problems:

  1. examine numWays[i-1] and the validity of s[i];
    if ( s[i] != '0' ) numWays[i] += numWays[i-1];
    
  2. examine numWays[i-2] and the validity of s.substr(i-1, 2).
    if ( s[i-1] != '0' and atoi(s.substr(i-1, 2).c_str()) <= 26 ) numWays[i] += numWays[i-2];
    
class Solution {
public:
    int help1(string s) {
        if ( s != "0" ) return 1;
        return 0;
    }
    int help2(string s) {
        if ( s[0] == '0' ) return 0;
        int i = stoi(s);
        if ( i > 26 ) return 0;
        return 1;
    }
    int numDecodings(string s) {
        int n = s.size();
        vector<int> res(n+1, 0);
        if ( n == 0 ) return 0;
        res[0] = 1;
        for ( int i = 0; i <= n; i++ ) {
            if ( i+1 <= n ) res[i+1] += res[i]*help1(s.substr(i, 1));
            if ( i+2 <= n ) res[i+2] += res[i]*help2(s.substr(i, 2));
        }
        return res[n];
    }
};

results matching ""

    No results matching ""