LeetCode(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.

Some examples:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

分析如下:

使用stack的基础型题目。


我的代码:

//80ms
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        int i = 0;
        int operand1 = 0;
        int operand2 = 0;
        stack<int> operand_stack;
        while (i < tokens.size()) {
            if (tokens[i] == "+") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 + operand1);
            } else if (tokens[i] =="-") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 - operand1);
            } else if(tokens[i] == "*") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 * operand1);
            } else if (tokens[i] == "/") {
                operand1 = operand_stack.top();
                operand_stack.pop();
                operand2 = operand_stack.top();
                operand_stack.pop();
                operand_stack.push(operand2 / operand1);
            } else {
                operand1 = atoi(tokens[i].c_str());
                operand_stack.push(operand1);
            }
            i++;
        }
        return operand_stack.top();
    }
};


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