跳到主要内容

Evaluate Reverse Polish Notation

描述

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

分析

逆波兰表达式是典型的递归结构,所以可以用递归来求解,也可以用栈来求解。

代码

递归版

# Evaluate Reverse Polish Notation
# Recursive
# Time Complexity: O(n),Space Complexity: O(n)
class Solution:
def evalRPN(self, tokens: list[str]) -> int:
self.top = len(tokens) - 1
return self.dfs(tokens)

def dfs(self, tokens: list[str]) -> int:
token = tokens[self.top]
self.top -= 1
if token not in "+-*/":
return int(token)
else:
y = self.dfs(tokens)
x = self.dfs(tokens)
if token == "+": return x + y
elif token == "-": return x - y
elif token == "*": return x * y
else: return int(x / y)

// Evaluate Reverse Polish Notation
// UsingStack
// Time Complexity: O(n),Space Complexity: O(n)
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<>();
for (String token : tokens) {
if (!"+-*/".contains(token)) {
s.push(Integer.valueOf(token));
} else {
int y = s.pop();
int x = s.pop();
switch (token) {
case "+": x += y; break;
case "-": x -= y; break;
case "*": x *= y; break;
default: x /= y;
}
s.push(x);
}
}
return s.peek();
}
}