Basic Calculator

题目地址:
https://leetcode.com/problems/basic-calculator/#/description

题目:
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来存符号和rst。

代码:



public int calculate(String s) {
    int len = s.length(), sign = 1, rst = 0;
    Stack<Integer> stack = new Stack<Integer>();
    for(int i = 0; i < len; i++){
        if(Character.isDigit(s.charAt(i))){
            int temp = s.charAt(i) - '0';
            while((i + 1) < len && Character.isDigit(s.charAt(i + 1))){
                temp = temp * 10 + (s.charAt(i + 1) - '0');
                i++;
            }
            rst += temp * sign;
        }
        else if(s.charAt(i) == '+'){
            sign = 1;
        }
        else if(s.charAt(i) == '-'){
            sign = -1;
        }
        else if(s.charAt(i) == '('){
            stack.push(rst);
            stack.push(sign);
            rst = 0;
            sign = 1;
        }
        else if(s.charAt(i) == ')'){
            rst = rst * stack.pop() + stack.pop();
        }
    }
    return rst;
}



Comments

Popular Posts