美文网首页
227. Basic Calculator II

227. Basic Calculator II

作者: jluemmmm | 来源:发表于2021-12-09 17:53 被阅读0次
    • 时间复杂度O(n),空间复杂度O(n)
    • Runtime: 96 ms, faster than 62.50%
    • Memory Usage: 48.1 MB, less than 8.93%

    类似加减乘除的计算方式,对括号里面的内容进行递归。parseInt在遇到非常小的数字的时候会出现不符合预期的异常情况,换成 |0

    /**
     * @param {string} s
     * @return {number}
     */
    var calculate = function(s) {
      while(s.indexOf(')') > 0) {
        let end = s.indexOf(')');
        let start = s.substring(0, end).lastIndexOf('(');
        let cur = help(s.substring(start + 1, end));
        s = s.substring(0, start) + cur + s.substring(end + 1);
      }
      return help(s);
    };
    
    var help = function(s) {
      s = s.replace(/\s/g, '');
      let sign = '+';
      let stack = [];
      let res = 0;
      let len = s.length;
      let num = 0;
      let prev = ''
      for (let i = 0; i < len; i++) {
        let start = i;
        while (/[0-9]/.test(s[i]) || /[*/+-]/.test(s[i - 1]) && s[i] === '-') {
          i++;
        }
        const num = s.substring(start, i) - '0';
        switch(sign) {
          case '+':
            stack.push(num);
            break;
          case '-':
            stack.push(-num);
            break;
          case '*':
            stack.push(stack.pop() * num);
            break;
          case '/':
            stack.push((stack.pop() / num) | 0);
            break;
        }
        sign = s[i];
      }
      while (stack.length) {
        res += stack.pop();
      }
      return res + '';
    };
    

    相关文章

      网友评论

          本文标题:227. Basic Calculator II

          本文链接:https://www.haomeiwen.com/subject/reexfrtx.html