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

逆波兰表达式,比较简单,编译原理。

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> operands;
        operands.push(0);
        int operand1, operand2;
        for (int i = 0; i < tokens.size(); ++i) {
            if (tokens[i] == "+") {
                getOperands(operands, operand1, operand2);
                operands.push(operand1 + operand2);
            }
            else if (tokens[i] == "-") {
                getOperands(operands, operand1, operand2);
                operands.push(operand1 - operand2);
            }
            else if (tokens[i] == "*") {
                getOperands(operands, operand1, operand2);
                operands.push(operand1 * operand2);
            }
            else if (tokens[i] == "/") {
                getOperands(operands, operand1, operand2);
                operands.push(operand1 / operand2);
            }
            else {
                operands.push(atoi(tokens[i].c_str()));
            }
        }
        
        return operands.top();
    }
    
    void getOperands(stack<int> &operands, int &op1, int &op2) {
        op2 = operands.top();
        operands.pop();
        op1 = operands.top();
        operands.pop();
    }
};

====================第二次============================
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> operands;
        for (int i = 0; i < tokens.size(); ++i) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                int op2 = operands.top();
                operands.pop();
                int op1 = operands.top();
                operands.pop();
                operands.push(eval(tokens[i][0], op1, op2));
            }
            else {
                operands.push(atoi(tokens[i].c_str()));
            }
        }
        
        return operands.top();
    }
    
    int eval(char action, int op1, int op2) {
        int result = 0;
        switch (action) {
        case '+':
            result = op1 + op2;
            break;
        case '-':
            result = op1 - op2;
            break;
        case '*':
            result = op1 * op2;
            break;
        case '/':
            result = op1 / op2;
            break;
        }
        
        return result;
    }
};


你可能感兴趣的:(LeetCode)