Leetcode 150. Evaluate Reverse Polish Notation

在这里插入图片描述
方法1: stack。还是比较容易想到stack的,因为是reverse polish notion,其实这就是postfix表达式,然后还约等于tree里面的postorder traversal。时间复杂n,空间复杂n。

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        stack.push(tokens[0]);
        for(int i = 1; i < tokens.length; i++){
            String curr = tokens[i];
            stack.push(curr);
            if(curr.equals("+")){
                stack.pop();
                int d1 = Integer.parseInt(stack.pop());
                int d2 = Integer.parseInt(stack.pop());
                String s = String.valueOf(d2 + d1);
                stack.push(s);
            }else if(curr.equals("-")){
                stack.pop();
                int d1 = Integer.parseInt(stack.pop());
                int d2 = Integer.parseInt(stack.pop());
                String s = String.valueOf(d2 - d1);
                stack.push(s);
            }else if(curr.equals("*")){
                stack.pop();
                int d1 = Integer.parseInt(stack.pop());
                int d2 = Integer.parseInt(stack.pop());
                String s = String.valueOf(d2 * d1);
                stack.push(s);
            }else if(curr.equals("/")){
                stack.pop();
                int d1 = Integer.parseInt(stack.pop());
                int d2 = Integer.parseInt(stack.pop());
                String s = String.valueOf(d2 / d1);
                stack.push(s);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

总结:

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页