150. Evaluate Reverse Polish Notation (Medium)

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

Solution: Stack 9ms

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;
        for (int i = 0; i < tokens.size(); ++i) {
            if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") {
                s.push(stoi(tokens[i]));
            } else {
                int b = s.top(); s.pop();
                int a = s.top(); s.pop();

                if (tokens[i] == "+") s.push(a+b);
                else if (tokens[i] == "-") s.push(a-b);
                else if (tokens[i] == "*") s.push(a*b);
                else if (tokens[i] == "/") s.push(a/b);

            }
        }
        return s.top();
    }
};

results matching ""

    No results matching ""