LeetCode题解——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> s;
        int v1,v2;
        for(auto c:tokens){
            if(c=="*"){
                v1 = s.top(); s.pop();
                v2 = s.top(); s.pop();
                s.push(v1*v2);
            }
            else if(c=="/"){
                v1 = s.top(); s.pop();
                v2 = s.top(); s.pop();
                s.push(int(v2/v1));
            }
            else if(c=="+"){
                v1 = s.top(); s.pop();
                v2 = s.top(); s.pop();
                s.push(v1+v2);
            }
            else if(c=="-"){
                v1 = s.top(); s.pop();
                v2 = s.top(); s.pop();
                s.push(v2-v1);
            }
            else s.push(stoi(c));
        }
        return s.top();
    }
};


你可能感兴趣的:(LeetCode,stack)