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

逆波兰表达式求值

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

全部评论

相关推荐

被加薪的哈里很优秀:应该继续招人,不会给你留岗位的
点赞 评论 收藏
分享
03-05 12:52
吉林大学 Java
挣K存W养DOG:他的价值在于把他家里积攒的财富回馈给社会
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务