LC150 - Evaluate Reverse Polish Notation
Last updated
Last updated
You are given an array of strings tokens
that represents an arithmetic expression in a .
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
The valid operators are '+'
, '-'
, '*'
, and '/'
.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Use a stack to hold tokens as we parse through the list of tokens. When an operation is encountered, pop two elements from the stack and run the operation. Order of operands matter for division and subtraction. Since we're popping from the end of the stack, the order is reversed. Use temporary variables to hold the popped values and flip them for the calculation.
Time complexity is and space complexity is an additional of stack space at worst.