Leetcode 之Evaluate Reverse Polish Notation(41)

很简单的一道题,定义一个栈保留操作数,遇操作符则弹出运算即可。

bool isOperator(string &op)
      {
          //注意用法
          return op.size() == 1 && string("+-*/").find(op) != string::npos;
      }
      int evalRPN(vector<string> &tokens)
      {
          stack<string> s;
          for (auto token : tokens)
          {
              if (!isOperator(token))
              {
                  //如果是操作数,则入栈
                  s.push(token);
              }
              else
              {
                  //如果是操作符,则弹出操作数进行运算
                  int y = stoi(s.top());
                  s.pop();
                  int x = stoi(s.top());
                  s.pop();
                  if (token == "+")x += y;
                  if (token == "-")x -= y;
                  if (token == "*")x *= y;
                  if (token == "/")x /= y;
                  s.push(to_string(x));
              }
          }
          return stoi(s.top());
      }
View Code
原文地址:https://www.cnblogs.com/573177885qq/p/5537374.html