Wednesday, November 27, 2013

Evaluate Reverse Polish Notation [Leetcode]

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

Solution: I implemented the algorithm provided in Reverse Polish Notation.
class Solution {
public:
    bool isOperator(string token){
        return token=="+" || token=="-" || token=="*" || token=="/";
    }
    int cal(int lOperand, int rOperand, string op){
        if(op=="+")
            return lOperand+rOperand;
        if(op=="-")
            return lOperand-rOperand;
        if(op=="*")
            return lOperand*rOperand;
        return lOperand/rOperand;
    }
    int evalRPN(vector<string> &tokens) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(tokens.empty())
            return INT_MIN;
        stack<int> s;
        for(size_t i=0; i<tokens.size(); ++i){
            if(isOperator(tokens[i])){
                if(s.size()>=2){
                    int rOperand = s.top();
                    s.pop();
                    int lOperand = s.top();
                    s.pop();
                    s.push(cal(lOperand, rOperand, tokens[i]));
                }
                else
                    return INT_MIN;
            }
            else
                s.push(stoi(tokens[i]));
        }
        if(s.size()==1)
            return s.top();
        return INT_MIN;
    }
}; 

No comments:

Post a Comment