224. Basic Calculator

Posted 鱼与海洋

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.

 

分析:

 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的主要内容,如果未能解决你的问题,请参考以下文章

224. Basic Calculator

Leetcode 224: Basic Calculator

[LC] 224. Basic Calculator

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

leetcode-Basic Calculator-224

[LeetCode] 224. 基本计算器