Short but slow JavaScript abusing replacements


  • 0
    var calculate = function(s, u = 'dummy') {
        s = s.replace(/-/g, '+-');
        while (s !== (u = unparen(s))) s = u;
        return s.split('+').reduce((sum, a) => sum + parseInt(a || 0), 0);
    };
    
    function unparen(s) {
        return s
            .replace(/(?:^|\+) *\(([^(]+?)\)/g, (match, inner) => '+' + inner)
            .replace(/- *\(([^(]+?)\)/g, (match, inner) => '-' + inner.replace(/\+/g, '+-').replace(/--/g, ''));
    }
    

    Ultimately this is a fancy eval. If we were only dealing with + we could kill all parentheses and use associativity. Since we aren't, we use unparen to distribute the -1 until there are no more -(expression)'s.

    A similar approach for Basic Calculator II is found here.


Log in to reply
 

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