LeetCode - 224. Basic Calculator

1. 问题描述

  • 描述:给出一个算数表达式字符串,计算其结果。字符串由’+’、’-’、’ ‘、’(’、’)'组成。
  • 输入:表达式字符串
  • 输出:表达式计算结果

2. 解题思路

  • 关键点:解析字符串、计算结果
  • 解题步骤:
    • a. 解析字符串
    • b. 计算括号内结果
    • c. 计算最终结果

javascript:

var calculate = function (s) {
    if (s.length === 0) {
        return 0;
    }

    let arr = pareToArray(s);

    let stack = [];
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i] !== '(') {
            if (arr[i] === '-') {
                stack.push(false);
            } else if (arr[i] === '+') {
                stack.push(true)
            } else if (arr[i] === ')') {
                stack.push(arr[i])
            } else if (arr[i] !== ' ') {
                stack.push(Number(arr[i]));
            }
        } else {
            calculateWithoutBracket(stack);
        }
    }
    calculateWithoutBracket(stack);
    return stack.pop();
};

var pareToArray = function (s) {
    if (s[0] === '-' || s[0] === '+') {
        s = 0 + s;
    }

    let arr = [];
    for (let i = 0; i < s.length; i++) {
        if (s[i] === ' ') {
            continue;
        }
        if (isNaN(Number(s[i]))) {
            arr.push(s[i]);
        } else {
            if (isNaN(Number(arr[arr.length - 1]))) {
                arr.push(s[i]);
            } else {
                arr[arr.length - 1] += s[i];
            }
        }
    }
    return arr;
}

var calculateWithoutBracket = function (stack) {
    let tempSum = stack.pop();
    while (stack.length !== 0 && stack[stack.length - 1] !== ')') {
        let item = stack.pop();
        if (item === false) {
            tempSum -= stack.pop();
        } else {
            tempSum += stack.pop();
        }
    }

    if (stack[stack.length - 1] === ')') {
        stack.pop();
    }

    stack.push(tempSum);
}

3. 备注

程序还有待优化…

上一篇:Calculator Conundrum UVA - 11549(floyd判圈)


下一篇:Antenna Calculator