Leecode 150.逆波兰表达式求值

题目

在这里插入图片描述
添加链接描述

解题思路

  • 从前向后遍历数组
  • 遇到数字则压入栈中
  • 遇见计算符则将栈顶的前两个字符进行运算,结果再加入栈中
  • 遍历数组到最后,栈顶元素即为最后答案
public class Solution {
    public int EvalRPN(string[] tokens) {
            //创建一个数据栈
            Stack<int> data = new Stack<int>();
            for (int i = 0; i < tokens.Length; i++)
            {
                if (tokens[i] == "+" || tokens[i] == "/" || tokens[i] == "-" || tokens[i] == "*")
                {
                    int a = data.Pop();
                    int b = data.Pop();
                    if (tokens[i] == "+")
                    {
                        data.Push(b + a);
                    }
                    if (tokens[i] == "-")
                    {
                        data.Push(b - a);
                    }
                    if (tokens[i] == "*")
                    {
                        data.Push(b * a);
                    }
                    if (tokens[i] == "/")
                    {
                        data.Push(b / a);
                    }
                }
                else
                    data.Push(int.Parse(tokens[i]));

            }
            return data.Pop();

    }
}

在这里插入图片描述

发布了52 篇原创文章 · 获赞 5 · 访问量 3971

猜你喜欢

转载自blog.csdn.net/Pang_ling/article/details/105040006
今日推荐