首页 > 代码库 > 224. Basic Calculator

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.

 

分析:

 one pass 

1. curNum  存目前的值

2. 遇到 + - , res += curNum * sign , sign 存+-

3.有()用一个stack存目前的res 和sign;

// res curNum 0 - 9 ; 10 -...
public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        int res = 0;
        int curNum = 0;
        int sign = 1;
        for(int i = 0 ; i < s.length(); i++){
            char temp = s.charAt(i);
            if(temp == ‘ ‘) 
                continue;
            else if(Character.isDigit(temp)) 
                curNum = curNum * 10 + (int) (temp - ‘0‘);
            else if( temp ==  ‘+‘){
                res += sign * curNum;
                curNum = 0;
                sign = 1;
            }
            else if(temp == ‘-‘){
                res += sign * curNum;
                curNum = 0;
                sign = -1;  //prepare for ();
            }
            else if(temp == ‘(‘){
                stack.push(res);
                stack.push(sign);
                res = 0;
                curNum = 0;
                sign = 1;
            }
            else if(temp == ‘)‘){
                res += curNum * sign;
                if(!stack.isEmpty())
                    sign = stack.pop();
                if(!stack.isEmpty())
                    res = res * sign + stack.pop();
                curNum = 0;
                sign = 1;
            }
        }
        if(curNum != 0)
            res += curNum * sign;
            
        return res;
    }
}

 

224. Basic Calculator