【Lintcode】424. Evaluate Reverse Polish Notation

题目地址:

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

给定一个逆波兰表达式,返回其值。按照逆波兰表达式的定义,直接用栈即可。代码如下:

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

时空复杂度 O ( n ) O(n)

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105428692