In postfix notation (also called reverse Polish notation) an operator is written after the two values it works on: 3 + 4 becomes 3 4 +. No brackets are ever needed, because each operator acts on the two values produced just before it.
You are given such an expression as a list of strings, tokens. Each token is either a whole number or one of the four operators "+", "-", "*" and "/". Work out the value of the expression and return it.
8 2 - is 8 - 2./ is whole-number division that drops the fractional part, rounding toward zero: 7 / 2 is 3 and -7 / 2 is -3.* takes the two values just before it, 3 and 4, giving 12. Then + takes 2 and 12, giving 14. In ordinary notation this is 2 + 3 * 4.
7 2 - is 7 - 2 = 5, and then 5 4 * is 20: (7 - 2) * 4.
10 - 5 = 5, then 4 * 5 = 20. Last, 20 / -6 is -3.33…, and dropping the fraction gives -3. The token "-6" is a number; only a "-" on its own is the operator.
Constraints
1 <= tokens.length <= 10⁴"+", "-", "*", "/", or a whole number from -200 to 200 written in plain digits: a leading - for a negative number, never a + sign or a leading zero.tokens is a valid postfix expression: every operator has two values before it, and exactly one value is left at the end.Read the tokens left to right and keep the values not yet used on a stack. Each operator works on exactly the two most recent of them.
In postfix, an operator always comes right after its two operands, and those operands are values that are already finished. So the leftmost operator is easy to evaluate: the two items just before it are plain numbers. Work it out, replace the three items with the result, and the list is a shorter postfix expression with the same value. Repeat until one number is left.
Time O(n)Space O(n)
The full walkthrough and code are part of Premium
14