Leetcode - 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.

[balabala] 这题更像是考察编程缜密度的。思路是:逆序遍历字符串,数字和右括号保存在一个堆栈stack1中,运算符保存在另一个堆栈stack2中,跳过空格,遇到左括号时计算stack1中首个右括号之上的所有数据,也即当前括号对中的内容。 在Accept之前有两个出错点:1)采用顺序遍历。出错case:2-1+1,因为加减的运算顺序是从左至右;2)逆序遍历时拼接完一个位数大于1的完整int 后要逆序已得到实际数值。出错case: 2147483647

public int calculate(String s) {
        if (s == null || s.equals(""))
            return 0;
        LinkedList<String> stack1 = new LinkedList<String>();
        LinkedList<Character> stack2 = new LinkedList<Character>();
        int n = s.length();
        int i = n - 1;
        while (i >= 0) {
            StringBuilder num = new StringBuilder();
            char c = s.charAt(i);
            while (c >= '0' && c <= '9') {
                num.append(c);
                i--;
                if (i >= 0)
                    c = s.charAt(i);
                else
                    break;
            }
            if (num.length() > 0)
                stack1.push(num.reverse().toString());
            if (i < 0)
                break;
                
            c = s.charAt(i);
            if (c == ')') {
                stack1.push(")");
            } else if (c == '(') {
                while (!stack1.peek().equals(")")) {
                    sum(stack1, stack2);
                }
                stack1.pop();
            } else if (c == '+' || c == '-') {
                stack2.push(c);
            }
            i--;
        }
        while (!stack2.isEmpty()) {
            sum(stack1, stack2);
        }
        return !stack1.isEmpty() ? Integer.valueOf(stack1.pop()) : 0;
    }
    private void sum(LinkedList<String> stack1, LinkedList<Character> stack2) {
        int num1 = Integer.valueOf(stack1.pop());
        if (stack1.peek().equals(")")) {
            stack1.pop();
            stack1.push(String.valueOf(num1));
            stack1.push(")");
            return;
        }
        int num2 = Integer.valueOf(stack1.pop());
        char op = stack2.pop();
        if (op == '+')
            stack1.push(String.valueOf(num1 + num2));
        else
            stack1.push(String.valueOf(num1 - num2));
    }

 

 

你可能感兴趣的:(LeetCode)