Leecode 150. Reverse Polish expression evaluation

topic

Here Insert Picture Description
Add a link description

Problem-solving ideas

  • The former through the array backwards
  • Digital encounter is pushed onto the stack
  • The first two characters meet the top of the stack will be calculated symbol calculation result together with the stack
  • Through the array in the end, the top element is the final answer
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();

    }
}

Here Insert Picture Description

Published 52 original articles · won praise 5 · Views 3971

Guess you like

Origin blog.csdn.net/Pang_ling/article/details/105040006