Skip to content

224. Basic Calculator

Jacky Zhang edited this page Sep 9, 2016 · 1 revision

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.

解题思路为采用stack,遇上'('时,保存现场,遇上')'时,将之前结果从stack中取出再做运算。

public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0) return 0;
        int len = s.length();
        int res = 0, sign = 1;
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < len; i++) {
            if(Character.isDigit(s.charAt(i))) {
                int num = s.charAt(i) - '0';
                while(i+1 < len && Character.isDigit(s.charAt(i+1))) {
                    num = num * 10 + s.charAt(i+1) - '0';
                    i++;
                }
                res += num * sign;
            } else if(s.charAt(i) == '+') {
                sign = 1;
            } else if(s.charAt(i) == '-') {
                sign = -1;
            } else if(s.charAt(i) == '(') {
                stack.push(res);
                stack.push(sign);
                res = 0;
                sign = 1;
            } else if(s.charAt(i) == ')') {
                sign = stack.pop();
                res = res * sign + stack.pop();
            }
        }
        return res;
    }
}
Clone this wiki locally