Java, 10ms, beats 98%, O(1) space solution.


  • 0
    I
    /*
     * No need of stack.
     * Maintain a product and a op.
     * If met +-, based on op add num to ans or operate on product then add it to ans.
     * If met /*, based on op set product or operate on product.
     */
    public class Solution {
        public int calculate(String s) {
            int ans = 0, num = 0, product = 1, op = 1; // op 1: +; -1: -; 2: *; 3: /
            for (char c: s.toCharArray()) {
                switch(c) {
                    case ' ':
                        break;
                    case '+':
                    case '-':
                        ans += op == 2 ? product*num : op == 3 ? product/num : op*num;
                        op = c == '+' ? 1 : -1;
                        num = 0;
                        break;
                    case '*':
                    case '/':
                        product = op == 2 ? product*num : op == 3 ? product/num : op*num;
                        op = c == '*' ? 2 : 3;
                        num = 0;
                        break;
                    default:
                        num = num * 10 + c-'0';
                        break;
                }
            }
            ans += op == 2 ? product*num : op == 3 ? product/num : op*num;
            return ans;
        }
    }
    

Log in to reply
 

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