Re: [闲聊] 每日LeetCode

楼主: SecondRun (雨夜琴声)   2024-01-30 19:58:45
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;
}
}
作者: oin1104 (是oin的说)   2024-01-30 20:01:00
我永远喜欢stack姐姐

Links booklink

Contact Us: admin [ a t ] ucptt.com