LeetCode Evaluate Reverse Polish Notation

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.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

本题要对一个逆波兰表达式求值。简单题,借助一个堆栈,遇到数字压栈,遇到操作符,把栈顶两个元素弹栈并进行运算。需要注意的是,假设先后弹出来的两个元素是v1,v2,则后续的所有操作都应该是v2 op v1,不要搞错了。 完整代码如下:

class Solution {
public:
    int evalRPN(vector<string>& tokens)
    {
        stack<int> expression;
        for (size_t i = 0; i < tokens.size(); ++i) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                int v1 = expression.top();
                expression.pop();
                int v2 = expression.top();
                expression.pop();
                if (tokens[i] == "+")
                    expression.push(v2 + v1);
                else if (tokens[i] == "-")
                    expression.push(v2 – v1);
                else if (tokens[i] == "*")
                    expression.push(v2 * v1);
                else if (tokens[i] == "/")
                    expression.push(v2 / v1);
            }
            else
                expression.push(atoi(tokens[i].c_str()));
        }
        return expression.top();
    }
};

本代码提交AC,用时9MS。

Leave a Reply

Your email address will not be published. Required fields are marked *