LC150 - Evaluate Reverse Polish Notation
Problem
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.
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.
Example
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Solution
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.
Last updated