Problem 150
Question statement
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation. Evaluate the expression. Return an integer that represents the value of the expression.
Solution
Main idea:
Create a stack. Scan the tokens array. Push tokens[i] into the stack if it is a number. If it is an operation, instead, pop the last two elements from the stack, perform the operation, and then push the result into the stack. Continue this way until the stack is exhausted.
Code:
1 | def calculator(self,a, b, op): |
Comments:
Time complexity: O(n)
At the time of submission, the above solution passes leetcode submission cases in 63ms, beats 82.29% of users. It uses 17.10MB of memory, beating 71.20% of users.