150.Evaluate Reverse Polish Notation
直接看example
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
C# code:
https://i.imgur.com/XNoiGMm.png
public class Solution
{
public int EvalRPN(string[] tokens)
{
Stack<int> stack = new Stack<int>();
int a, b;
foreach (string token in tokens)
{
if (int.TryParse(token, out int value))
{
stack.Push(value);
continue;
}
b = stack.Pop();
a = stack.Pop();
stack.Push(Calculate(a, b, token));
}
return stack.Pop();
}
public int Calculate(int a, int b, string op)
{
switch (op)
{
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
}
return -1;
}
}