LeetCode 150. 逆波兰表达式求值 (C#实现)

问题:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

GitHub实现:https://github.com/JonathanZxxxx/LeetCode/blob/master/EvalRPNClass.cs

一、逆波兰式

二、逆波兰式求值
思路:从左至右遍历整个字符串,数字入栈,遇到操作符取栈首两个数字求值后再次压栈

        public int EvalRPN(string[] tokens)
        {
            var value = new Stack<int>();
            foreach (var s in tokens)
            {
                if (s != "+" && s != "-" && s != "*" && s != "/")
                {
                    value.Push(Convert.ToInt32(s));
                    continue;
                }
                var a = value.Pop();
                var b = value.Pop();
                switch (s)
                {
                    case "+": value.Push(b + a); break;
                    case "-": value.Push(b - a); break;
                    case "*": value.Push(b * a); break;
                    case "/": value.Push(b / a); break;
                    default: break;
                }
            }
            return value.Pop();
        }    

猜你喜欢

转载自www.cnblogs.com/zxxxx/p/10537000.html
今日推荐