【Lintcode】424. Evaluate Reverse Polish Notation

Title address:

https://www.lintcode.com/problem/evaluate-reverse-polish-notation/description

Given an inverse Polish expression, return its value. According to the definition of the reverse Polish expression, just use the stack directly. code show as below:

import java.util.*;

public class Solution {
    /**
     * @param tokens: The Reverse Polish Notation
     * @return: the value
     */
    public int evalRPN(String[] tokens) {
        // write your code here
        Deque<Integer> stack = new LinkedList<>();
        Set<String> operators = new HashSet<>(Arrays.asList("+", "-", "*", "/"));
        for (int i = 0; i < tokens.length; i++) {
            if (!operators.contains(tokens[i])) {
                stack.push(Integer.parseInt(tokens[i]));
            } else {
                int b = stack.pop(), a= stack.pop();
                stack.push(cal(a, b, tokens[i]));
            }
        }
        
        return stack.peek();
    }
    
    private int cal(int a, int b, String op) {
        switch (op) {
            case "+": return a + b;
            case "-": return a - b;
            case "*": return a * b;
            case "/": return a / b;
            default: return 0;
        }
    }
}

Space-time complexity THE ( n ) O (n)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105428692