[力扣] 算法 150 (C#)

150. 逆波兰表达式求值

public class Solution
{
    public int EvalRPN(string[] tokens)
    {
        var stack = new Stack<int>();
        foreach (var token in tokens)
        {
            switch (token)
            {
                case var add when add == "+":
                    stack.Push(stack.Pop() + stack.Pop());
                    break;
                case var minus when minus == "-":
                    stack.Push(-stack.Pop() + stack.Pop());
                    break;
                case var mul when mul == "*":
                    stack.Push(stack.Pop() * stack.Pop());
                    break;
                case var div when div == "/":
                    var top = stack.Pop();
                    stack.Push(stack.Pop() / top);
                    break;
                default:
                    stack.Push(int.Parse(token));
                    break;
            }
        }
        return stack.Pop();
    }
}

发表评论