[LeetCode-JAVA] 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.

题意:设计一个简易计算器,只有正数,运算符为"+" "-" "()" ,输入为string,去掉无用的空格后,给定的算式一定是合法的

思路1(顺序求解):为了将有括号和无括号的进行合并计算,认为的在string两端加上一对(),方便计算,同时考虑都数字可能很多位,这时需要切分出每一个数字和符号,因此要设计两个stack,分别存放数字和运算符,然后每当遇到右括号的时候进行计算,由于正常的计算应该是自左向右,所以在计算的过程中,应该每一位进行计算,而不是弹出两位进行计算。

例如: (2 - 1 + 2)

正确的计算顺序为 + 2 - 1 最后char的stacj遇到左括号 在 + 2

错误的计算书序为 1 + 2 结果存入a 之后再 2 - a 显然是错误的 需要细细体会

最后istack中的数字即为结果。

代码1:

public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0)
            return 0;
        s = "(" + s + ")";
        Stack<Character> cstack = new Stack<Character>();
        Stack<Integer> istack = new Stack<Integer>();
        
        boolean isNum = false;
        int sum = 0;
        
        for(int i = 0 ; i < s.length() ; i++){
            if(s.charAt(i) == ' ')
                continue;
            if(Character.isDigit(s.charAt(i))){
                sum = sum *10 + s.charAt(i) - '0';
                isNum = true;
                continue;
            }else if(isNum){  //考虑到会有 (( 连续的非数字情况 只需压入一次数字
                istack.push(sum);
                sum = 0;
                isNum = false;
            }
            
            if(s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '('){
                cstack.push(s.charAt(i));
            }else if(s.charAt(i) == ')'){
                int temp = 0;  // 每一次括号里的值
                while(cstack.peek() != '('){  //直到可以匹配的左括号
                    int a = istack.pop();
                    int c = cstack.pop();
                    if(c == '+'){
                        temp += a;
                    }else if(c == '-'){
                        temp -= a;
                    }
                }
                temp += istack.pop(); // 加上左括号后面的数字
                istack.push(temp);
                cstack.pop();
            }
        }
        
        return istack.pop();
    }
}

思路2(后缀表达式):通用的计算方式,将带括号的运算时转化为 不带括号的后缀表达式,之后用一个stack即可完成。

代码2: (刚有思路,代码debug中)...