227. Basic Calculator II

Basic Calculator II - LeetCode

Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example 1: Input: s = “3+2*2” Output: 7 Example 2: Input: s = " 3/2 " Output: 1 Example 3: Input: s = " 3+5 / 2 " Output: 5

Constraints:

1 <= s.length <= 3 * 105 s consists of integers and operators ('+', ‘-’, ‘*’, ‘/') separated by some number of spaces. s represents a valid expression. All the integers in the expression are non-negative integers in the range [0, 231 - 1]. The answer is guaranteed to fit in a 32-bit integer.


  • code
class Solution {
    public int calculate(String s) {
        char lastOp = '+';
        int lastNum = 0;
        int res = 0;
        int curNum = 0;
        
        for (int i = 0; i < s.length(); i++){
            char cur = s.charAt(i);
            if (Character.isDigit(cur)){
                curNum = curNum * 10 + (cur - '0');
            }
            if (!Character.isDigit(cur) && !Character.isWhitespace(cur) || i == s.length() - 1){
                if (lastOp == '+' || lastOp == '-'){
                    res += lastNum;
                    lastNum = (lastOp == '+') ? curNum : -curNum; // check lastOp here
                }
                else{
                    if (lastOp == '*'){
                        lastNum *= curNum;
                    }else{
                        lastNum /= curNum;
                    }
                }
                lastOp = cur;
                curNum = 0; // don't forget
            }
        }
        res += lastNum; // don't forget
        return res;
    }
}
  • code naive deque…
class Solution:
    def calculate(self, s: str) -> int:
        num = deque()
        operator = deque()
        
        last_dig = 0
        find_nex = False
        i = 0
        last_dig_continue = False
        while i < len(s):
            if s[i] == " ": 
                i += 1
                continue
            if find_nex:
                find_nex = False
                while i < len(s) and s[i].isdigit():
                    last_dig = last_dig * 10 + int(s[i])
                    i += 1
                op = operator.pop()
                last = num.pop() 
                if op == "*":
                    num.append(last * last_dig)
                else:
                    num.append(last // last_dig)
                last_dig = 0
                last_dig_continue = False
            else:
                if s[i].isdigit():
                    last_dig = last_dig * 10 + int(s[i])
                    last_dig_continue = True
                elif s[i] == "+" or s[i] == "-":
                    if last_dig_continue:
                        num.append(last_dig)
                    last_dig = 0
                    operator.append(s[i])
                elif s[i] == "*" or s[i] == "/":
                    if last_dig_continue:
                        num.append(last_dig)
                    last_dig = 0
                    find_nex = True
                    operator.append(s[i])
                i += 1 
        if last_dig_continue: num.append(last_dig)
        while num:
            if not operator: return num.pop()
            first, second = num.popleft(), num.popleft()
            op = operator.popleft()
            if op == "+":
                num.appendleft(first + second)
            else:
                num.appendleft(first - second)
        return ans