Logo

Brendan's Blog

Come for computer science and tech related blog posts.

Brendan Lichtler

1-Minute Read

Desert Scene

https://leetcode.com/problems/evaluate-reverse-polish-notation/

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Note that division between two integers should truncate toward zero.

It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.

Idea:

Solution:


class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<long> s;
        for (auto &token: tokens) {
            if (isOperator(token)) {
                long a = s.top();
                s.pop();
                long b = s.top();
                s.pop();
                s.push(compute(a, b, token[0]));
            } else {
                s.push(stol(token));
            }
        }
        return s.top();
    }

    long compute(long a, long b, char op) {
        switch(op) {
            case '+':
                return b + a;
            case '-': 
                return b - a;
            case '*':
                return b * a;
            default:
                return b / a;
        }
    }

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

Complexity Analysis:


Time

O(N)

Memory

O(N)

Say Something

Comments

Nothing yet.

Recent Posts

Categories

About

Blog designed for tech and computer science content.