【Lintcode】 424. Evaluar la notación polaca inversa

Dirección del título:

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

Dada una expresión polaca inversa, devuelve su valor. De acuerdo con la definición de la expresión polaca inversa, solo use la pila directamente. El código es el siguiente:

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;
        }
    }
}

Complejidad espacio-tiempo El ( norte ) O (n)

Publicado 387 artículos originales · me gusta 0 · 10,000+ visitas

Supongo que te gusta

Origin blog.csdn.net/qq_46105170/article/details/105428692
Recomendado
Clasificación