13ms JAVA solution, O(n) time, O(1) space


  • 0
    L
    public class Solution {
        private enum Action { MUL, DIV, ADD }
    
        public int calculate(String s) {
            int res = 0;
            int sign = 1;
            int last = 0;
            int pre = 1;
            Action act = Action.MUL;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == ' ') continue;
                if (c == '+' || c == '-') {
                    res += calc(act, pre, last) * sign;
                    act = Action.ADD;
                    pre = 1;
                    last = 0;
                    sign = c == '+' ? 1 : -1;
                } else if (c == '*' || c == '/') {
                    pre = calc(act, pre, last);
                    last = 0;
                    act = c == '*' ? Action.MUL : Action.DIV;
                } else {
                    int val = c - '0';
                    last = last * 10 + val;
                }
            }
            
            return res + calc(act, pre, last) * sign;
        }
        
        private int calc(Action act, int num1, int num2) {
            switch (act) {
                case ADD:
                    return num2;
                case MUL:
                    return num1 * num2;
                case DIV:
                    return num1 / num2;
            }
            return 0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.