题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

import java.util.*;


public class Solution {

    private static final Deque<Integer> stack = new ArrayDeque<>();
    public int evalRPN (String[] tokens) {
        // write code here
        for (int i = 0; i != tokens.length; ++i) {
            if (tokens[i].equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if (tokens[i].equals("-")) {
                int last = stack.pop();
                stack.push(stack.pop() - last);                
            } else if (tokens[i].equals("*")) {
                stack.push(stack.pop() * stack.pop());                                
            } else if (tokens[i].equals("/")) {
                int last = stack.pop();
                stack.push(stack.pop() / last);                     
            } else {
                stack.push(Integer.parseInt(tokens[i]));
            }
        }

        if (stack.isEmpty()) {
            return 0;
        }
        return stack.peek();
    }
}

全部评论

相关推荐

在喝茶的牛油很喜欢吃...:今天oc了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务