JavaScript RegExp Solution, faster than 73%


  • 0
    F
    var calculate = function(s) {
        s = s.replace(/\s+/g, '');
        var reg = /\(([^\(\)]+)\)/g; 
        while( ~s.indexOf('(') ) {
            // extract the expression in parentheses as long as there is parentheses
            // then calculate the expression in parentheses and replace it
            s = s.replace(reg, function($0, $1) {
                return cal($1);
            })
        }
        return cal(s);
    };
    
    // pass an expression without parentheses
    function cal(s) {
        var i = 0, l = s.length, c, cc, res = 0, tmp = '';
        while(i < l) {
            c = s.charAt(i);
            switch(c) {
                case '+':
                    cc = s.charAt(i+1);
                    res += +tmp;
                    tmp = cc === '+' ? '' : cc;
                    i += 2;
                    break;
                case '-':
                    cc = s.charAt(i+1);
                    res += +tmp;
                    tmp = cc === '+' ? '-' : cc === '-' ? '' : -cc;
                    i += 2;
                    break;
                default:
                    tmp += c;
                    i++;
            }
        }
        return res += +tmp;
    }
    

Log in to reply
 

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