Header Ad

Leetcode Evaluate Reverse Polish Notation problem solution

In this Leetcode Evaluate Reverse Polish Notation problem solution, we need to 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 the 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 a result, and there will not be any division by zero operation.

Leetcode Evaluate Reverse Polish Notation problem solution


Problem solution in Python.

import operator

class Solution:
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        
        if tokens == []:
            return -1
        
        stack = [] 
        
        ops = ["+", "-", "*", "/"]
        ops_lookup = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}
        
        for token in tokens:            
            if token not in ops:
                stack.append(int(token))
            else:
                val1 = stack.pop(-1)
                val2 = stack.pop(-1)
                result = ops_lookup[token](val2, val1)
                stack.append(int(result))
            
        return stack.pop()



Problem solution in Java.

public class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque();
        for (String s : tokens) {
            if (s.charAt(s.length() - 1) >= '0' && s.charAt(s.length() - 1) <= '9') {
                stack.push(Integer.valueOf(s));
            } else {
                int cur = stack.pop(), pre = stack.pop();
                stack.push(cal(pre, s.charAt(0), cur));
            }
        }
        return stack.pop();
    }
    
    private int cal(int a, char p, int b) {
        switch (p) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/': return a / b;
        }
        return -1;
    }
}


Problem solution in C++.

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;
        for ( const string& token: tokens ) {
            if (token == "+") {
                int rhs = s.top();
                s.pop();
                int lhs = s.top();
                s.pop();
                int res = lhs + rhs;
                s.push(res);
            } else if (token == "-") {
                int rhs = s.top();
                s.pop();
                int lhs = s.top();
                s.pop();
                int res = lhs - rhs;
                s.push(res);
            } else if (token == "/") {
                int rhs = s.top();
                s.pop();
                int lhs = s.top();
                s.pop();
                int res = lhs / rhs;
                s.push(res);
            } else if (token == "*") {
                int rhs = s.top();
                s.pop();
                int lhs = s.top();
                s.pop();
                int res = lhs * rhs;
                s.push(res);
            } else {
                s.push(stoi(token));
            }
        }
        return s.top();
    }
};


Problem solution in C.

int evalRPN(char ** tokens, int tokensSize){
    int s[10000], t = -1, r;
    for (int i = 0 ; i < tokensSize ; i++)
        if (!isdigit(tokens[i][0]) && !tokens[i][1]) {
            int p2 = s[t--], p1 = s[t--];
            switch (tokens[i][0]) {
                case '+': r = p1 + p2; break;
                case '-' : r = p1 - p2; break;
                case '*' : r = p1 * p2; break;
                case '/' : r = p1 / p2; break;
            }
            s[++t] = r;
        } else
            s[++t] = atoi(tokens[i]);
    return s[t--];
}


Post a Comment

0 Comments