Javascript Solution (100%)


  • 0
    A
    var numDecodings = function(s) {
        const n = s.split('').length;
        
        let pre2 = 1;
        let pre1 = 1;
        let cur;
    
        if (n === 0 || s[0] === '0') { 
            return 0;
        }
    
        if (n === 1) {
            return 1;
        }
        
        for (let i = 1; i < n; ++i) {
            let first = (s[i] - '0');
            let second = parseInt(s.substr(i - 1, 2));
    
            cur = 0;
    
            if (1 <= first && first <= 9) {
                cur += pre1;    
            }
            
            if (10 <= second && second <= 26) {
                cur += pre2;    
            }
            
            pre2 = pre1;
            pre1 = cur;
        }
    
        return cur;
    };
    

Log in to reply
 

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