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

Nothing special.....

#include <string>
#include <vector>
#include <stack>
#include <algorithm>
#include <iostream>
using namespace std;

bool isOPRD(string a) {
    return ! (a.size() == 1 && (a[0] == '*' || a[0] == '+' || a[0] == '-' || a[0] == '/'));
}

int caculate(int left, char a, int right) {
    if(a == '*') return left * right;
    else if(a == '+') return left + right;
    else if(a == '-') return right - left;
    else return right / left;
}

int evalRPN(vector<string>& tokens) {
    if(tokens.size() == 0) return 0;
    stack<int> OPRD;
    for(int i = 0; i < tokens.size(); ++i) {
        if(isOPRD(tokens[i])) {
            OPRD.push(stoi(tokens[i]));
        } else {
            int left = OPRD.top();
            OPRD.pop();
            int right = OPRD.top();
            OPRD.pop();
            int res = caculate(left, tokens[i][0], right);
            OPRD.push(res);
        }
    }
    return OPRD.top();
}

int main(void) {
    vector<string> tokens{"-1", "1", "*", "-1", "+"};
    int result = evalRPN(tokens);
    cout << result << endl;
}


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