150. Evaluate Reverse Polish Notation

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

【思路】建立一个栈,非符号压入栈,遇到符号,将栈中最顶的两个数操作后值再压入栈,最后返回栈顶元素。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
       stack<int> stk;
       if(tokens.size()==0) return 0;
       if(tokens.size()==1) return atoi(tokens[0].c_str());
       for(int i =0; i < tokens.size(); i++)
       {
           int tmp1,tmp2;
           if(tokens[i]!="+"&& tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/")
           {
              stk.push(atoi(tokens[i].c_str())); 
           }
           else if(tokens[i]=="+")
           {
               tmp1 = stk.top();
               stk.pop();
               tmp2 = stk.top();
               stk.pop();
               stk.push(tmp1 + tmp2);
           }
           else if(tokens[i]=="-"){
               tmp1 = stk.top();
               stk.pop();
               tmp2 = stk.top();
               stk.pop();
               stk.push(tmp2 - tmp1); 
           }
           else if(tokens[i]=="*")
           {
               tmp1 = stk.top();
               stk.pop();
               tmp2 = stk.top();
               stk.pop();
               stk.push(tmp2 * tmp1); 
           }
           else if(tokens[i]=="/")
           {
               tmp1 = stk.top();
               stk.pop();
               tmp2 = stk.top();
               stk.pop();
               stk.push(tmp2 / tmp1);  
           }
       }
       return stk.top();
    }
};


你可能感兴趣的:(150. Evaluate Reverse Polish Notation)