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:
    /**
     * @param tokens The Reverse Polish Notation
     * @return the value
     */
    int evalRPN(vector<string>& tokens) {
        // Write your code here
        int n = tokens.size();  
        if (n < 2)  
        {  
            return stoi(tokens[0]);  
        }  
          
        stack<int> buf;  
        int first, second;  
        for (int i = 0; i < n; i++)  
        {  
            if (isOperand(tokens[i]))  
            {  
                second = buf.top();  
                buf.pop();  
          
                first = buf.top();  
                second = cal(first, second, tokens[i]);  
                buf.pop();  
                
                buf.push(second);  
            }  
            else  
            {  
                buf.push(stoi(tokens[i]));  
            }  
        }  
  
        return second;  
    }
private:
    bool isOperand(string a)  
    {  
        if (a == "+" || a == "-"  
            || a == "*" || a == "/")  
        {  
            return true;  
        }  
  
        return false;  
    } 
    
    int cal(int a, int b, string c)  
    {  
        if (c == "+")  
        {  
            return a + b;  
        }  
        else if (c == "-")  
        {  
            return a - b;  
        }  
        else if (c == "*")  
        {  
            return a * b;  
        }  
        else  
        {  
            return a / b;  
        }  
    }  
};



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