LC224.基本计算器(辅助栈)

题目

题目

解题

  • 为了省去符号的倒序麻烦,使用两个栈来倒腾数字,这样最后的顺序就是顺序的,再用一个栈存储符号。
  • 每次遇到右括号执行以上的操作,即完成该括号对内的操作。
  • 为了能够存储多位整数和符号,用String来存储栈内元素。
class Solution {
    public int calculate(String s) {
        s = "("+s+")";
        Stack<String> stack = new Stack();
        for(int i = 0; i < s.length() ; i ++){
            if(s.charAt(i) == ' ') continue;
            if(s.charAt(i) != ')'){
                if(Character.isDigit(s.charAt(i))){
                    int t = 0;
                    while(Character.isDigit(s.charAt(i))){
                        t = t * 10 + s.charAt(i) - '0';
                        i += 1;
                    }
                    i -= 1;
                    stack.push(String.valueOf(t));
                    continue;
                }
                stack.push(s.charAt(i) + "");
            }else if(s.charAt(i) == ')'){
                Stack<String> helper1 = new Stack();
                Stack<Character> helper2 = new Stack();
                while(!stack.peek().equals("(")){
                    helper1.push(stack.pop());
                    if(!stack.peek().equals("("))
                    {
                        helper2.push(stack.pop().charAt(0));
                    }
                }
                stack.pop();
                int result = Integer.valueOf(helper1.pop());
                while(!helper1.isEmpty()){
                    int r = Integer.valueOf(helper1.pop());
                    result = helper2.pop() == '+' ? r + result : result - r;
                }
                stack.push(String.valueOf(result));
            }
        }
        return Integer.valueOf(stack.peek());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41423750/article/details/106952953