[leetcode代码]Evaluate Reverse Polish Notation

来源:互联网 发布:python人工智能模块 编辑:程序博客网 时间:2024/06/06 04:13

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


我自己写了递归实现,发现巨2.

贴一下别人的代码吧。

class Solution {      public:          int evalRPN(vector<string> &tokens) {              stack<int> numeric;                            for(auto& t : tokens)              {                  if (isdigit(t[0]) || t.size()>1)                      numeric.push(atoi(t.c_str()));                  else                  {                      int o1, o2;                      o2 = numeric.top();                      numeric.pop();                      o1 = numeric.top();                      numeric.pop();                                            switch(t[0])                      {                          case '+':                              numeric.push(o1 + o2);                              break;                          case '-':                              numeric.push(o1 - o2);                              break;                          case '*':                              numeric.push(o1 * o2);                              break;                          case '/':                              numeric.push(o1 / o2);                              break;                      }                  }              }                            return numeric.top();          }          };  



0 0