congr / world

2 stars 1 forks source link

LeetCode : 227. Basic Calculator II #458

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/basic-calculator-ii/ image

congr commented 5 years ago

O(N)

class Solution {
    public int calculate(String s) {
        s = s.replaceAll(" ", "");

        Stack<Integer> st = new Stack();
        char op = '+'; // input digits are non negative
        int e = 0, b = 0;

        while (e < s.length()) {
            while (e < s.length() && Character.isDigit(s.charAt(e))) e++;

            int n = Integer.parseInt(s.substring(b, e));
            if (op == '+') st.push(n);
            else if (op == '-') st.push(-1 * n);
            else { // * or /
                int p = st.pop(); 
                st.push (op == '*' ? p*n : p/n);
            }

            if(e < s.length()) op = s.charAt(e); // !!!
            b = ++e; // e is now at an operator, ++e is needed.
        }

        int num = 0;
        while (!st.isEmpty()) num += st.pop(); // for(int i : stack)
        return num;
    }
}