224. Basic Calculator

Posted 白天黑夜每日c

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了224. Basic Calculator相关的知识,希望对你有一定的参考价值。

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.


 

一般是无法顺序执行、有些数据无法处理、需要回头再来处理时用到栈。在这个计算器中,如果只有‘+’,‘-‘运算,可以顺序执行。碰到(),需要把括号里整个表达式算出来,因此对()要用栈来处理。

对含有+ - * /的运算符,因为* /的优先级高于+ -,碰到了* /,前一个运算符若是+ 或者-,它需要延迟计算,因此对所有都要用到栈。

public class Solution {
    public int calculate(String s) {
        Stack<Integer> nums = new Stack<Integer>();
        Stack<Character> ops = new Stack<Character>();
        int re = 0, num = 0;
        char op = ‘+‘;
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case ‘+‘:
                case ‘-‘:
                    if (op == ‘+‘) {
                        re = re + num;
                    } else {
                        re = re - num;
                    }
                    num = 0;
                    op = s.charAt(i);
                    break;
                case ‘(‘:
                    nums.push(re);
                    ops.push(op);
                    re = 0;
                    op = ‘+‘;
                    break;
                case ‘)‘:
                    if (op == ‘+‘) {
                        re = re + num;
                    } else {
                        re = re - num;
                    }
                    num = 0;
                    char c = ops.pop();
                    int prev = nums.pop();
                    if (c == ‘+‘) {
                        re = prev + re;
                    } else {
                        re = prev - re;
                    }
                    break;
                case ‘ ‘:
                    break;
                default:
                    num = 10 * num + s.charAt(i) - ‘0‘;
            }
        }
        if (num != 0) {
            if (op == ‘+‘) {
                return re + num;
            } else {
                return re - num;
            }
        }
        return re;
    }
}

 

以上是关于224. Basic Calculator的主要内容,如果未能解决你的问题,请参考以下文章

224. Basic Calculator

Leetcode 224: Basic Calculator

[LC] 224. Basic Calculator

[LeetCode]224. Basic Calculator(模拟,栈)

leetcode-Basic Calculator-224

[LeetCode] 224. 基本计算器