Wednesday, September 17, 2014

[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


Analysis:

Use a stack to store the numbers and pop out two numbers and do the operation whenever an operator was encountered. 

class Solution {
public:

    int doOperation(int op1, int op2, string theOperator)
    {
        if (theOperator == "+")
            return op1 + op2;
        else if (theOperator == "-")
            return op1 - op2;
        else if (theOperator == "*")
            return op1 * op2;
        else if (theOperator == "/")
            return op1 / op2;
        else
            return 0;
    }

    int evalRPN(vector &tokens) {
        stack s;
        for(int i=0; i < tokens.size();i++)
        {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
            {
                int op1 = s.top();
                s.pop();
                int op2 = s.top();
                s.pop();
                int r = doOperation(op2, op1, tokens[i]);
                s.push(r);
            }
            else
            {
                s.push(atoi(tokens[i].c_str()));
            }
        }
        
        return s.top();
    }
};

No comments:

Post a Comment