C implementation


  • 0
    C
    int numDecodings(char* s)
    {
        if ( !s ) {
            return 0;
        }
    
        int len = strlen( s );
        int m[ len + 1 ];
        int i;
        
        if ( !len || s[ 0 ] == '0' ) {
            return 0;
        }
    
        m[ 0 ] = 1;
        
        for ( i = 1; i <= len; i++ ) {
            int cur = s[ i - 1 ] - '0';
            int prev = s[ i - 2 ] - '0';
            m[ i ] = 0;
            if ( cur != 0 ) {
                m[ i ] = m[ i - 1 ];
            } else {
                if ( i < 2 || ( i > 1 && prev > 2 ) || ( i > 1 && prev == 0 ) ) {
                    return 0;
                }
            }
            if ( i > 1 ) {
                if ( prev!= 0 && prev * 10 + cur <= 26 ) {
                    m[ i ] += m[ i - 2 ];
                }
            }
        }
    
        return m[ len ];
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.