Count possible decodings of a given Digit Sequence | Set 2 | Function to count the number of ways to decode the given digit sequence ; Array to store the dp states ; Case of empty String ; Condition to check if the first character of String is 0 ; Base case for single length String ; Bottom - up dp for the String ; Previous character ; Current character ; Case to include the Current digit as a single digit for decoding the String ; Case to include the current character as two - digit for decoding the String ; Condition to check if the current character is " * " ; Condition to check if the current character is less than or equal to 26 ; Condition to check if the previous digit is equal to " * " ; Driver Code ; Function Call
function waysToDecode2 ( s ) { let n = s . length ; let dp = Array . from ( { length : n + 1 } , ( _ , i ) => 0 ) ; dp [ 0 ] = 1 ; if ( s [ 0 ] == ' ' ) return 0 ; dp [ 1 ] = ( ( s [ 0 ] == ' ' ) ? 9 : 1 ) ; for ( let i = 2 ; i <= n ; i ++ ) { let first = s [ i - 2 ] ; let second = s [ i - 1 ] ; if ( second == ' ' ) { dp [ i ] += 9 * dp [ i - 1 ] ; } else if ( second > ' ' ) dp [ i ] += dp [ i - 1 ] ; if ( first == ' ' first == ' ' ) { if ( second == ' ' ) { if ( first == ' ' ) dp [ i ] += 9 * dp [ i - 2 ] ; else if ( first == ' ' ) dp [ i ] += 6 * dp [ i - 2 ] ; } else if ( ( ( first - ' ' ) * 10 + ( second - ' ' ) ) <= 26 ) { dp [ i ] += dp [ i - 2 ] ; } } else if ( first == ' ' ) { if ( second == ' ' ) { dp [ i ] += 15 * dp [ i - 2 ] ; } else if ( second <= ' ' ) { dp [ i ] += 2 * dp [ i - 2 ] ; } else { dp [ i ] += dp [ i - 2 ] ; } } } return dp [ n ] ; } let str = " " ; document . write ( waysToDecode2 ( str . split ( ' ' ) ) + " " ) ;