227. Basic Calculator II


July-11-2019
跟带括号的区别还是蛮大的。
还是用了STACK,存所有+-的数,碰到*/就先POP出来算完再PUSH进去。

class Solution {
    private static final char INITIAL_SIGN = '+';
    public int calculate(String s) {
        if (s == null) return 0;
        int res = 0;
        int tempVal = 0;
        char sign = INITIAL_SIGN;
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        
        for (int i = 0; i < s.length(); i ++) {
            char tempChar = s.charAt(i);
            if (Character.isDigit(tempChar)) {
                while (i < s.length() && Character.isDigit(s.charAt(i))) {
                    tempVal = tempVal * 10 + s.charAt(i++) - '0';
                }
                if (i != s.length()) {
                    i --;
                }
                if (sign == '+') {
                    stack.push(tempVal);
                } else if (sign == '-') {
                    stack.push(-tempVal);
                } else if (sign == '*') {
                    stack.push(stack.pop() * tempVal);
                } else {
                    stack.push(stack.pop() / tempVal);
                }
                tempVal = 0;
            } else if (!isOperator(tempChar)) {
                continue;
            } else {
                sign = tempChar;
            }
        }
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }
    
    public boolean isOperator(char c) {
        return c == '+' || c == '-' || c == '*' || c == '/';
    }
}

三刷。

这次尝试把代码写的美观一些。。。

还是用stack,乘除就POP出一个再运算入栈,否则直接入栈。因为要运算,所以要记录上一个运算符号,第一个是+,因为STACK里所有的值都是+。

Time: O(n)

Space: O(n)

public class Solution {
    public int calculate(String s) {
        if (s.length() == 0) return 0;
        
        Stack<Integer> stk = new Stack<>();
        int temp = 0;
        char sign = '+';
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                temp = 10 * temp + c - '0';
            }
            if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {
                switch (sign) {
                    case '+':
                        stk.push(temp);
                        break;
                    case '-':
                        stk.push(-temp);
                        break;
                    case '*':
                        stk.push(stk.pop() * temp);
                        break;
                    case '/':
                        stk.push(stk.pop() / temp);
                        break;
                    default:
                        break;
                }
                sign = c;
                temp = 0;
            }
            
        } 
        
        int res = 0;
        while (!stk.isEmpty()) {
            res += stk.pop();
        }
        
        return res;
    }
}
posted @ 2016-12-08 12:36  哇呀呀..生气啦~  阅读(213)  评论(0编辑  收藏  举报