LeetCode227(2021.3.11)

LC227. 基本计算器 II

class Solution {
    public int calculate(String s) {
        Deque<Integer> stack = new LinkedList<Integer>();
        int num = 0;
        char op = '+';
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                num = num * 10 + s.charAt(i) - '0';
            }
            if (!Character.isDigit(s.charAt(i)) && s.charAt(i)!=' ' || i==s.length()-1) {
                if (op == '+') {
                    stack.push(num);
                }
                else if (op == '-') {
                    stack.push(-num);
                }
                else if (op == '*') {
                    stack.push(stack.pop() * num);
                }
                else {
                    stack.push(stack.pop() / num);
                }
                num = 0;
                op = s.charAt(i);
            }
        }
        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }
}

发表评论