题解 | 逆波兰表达式求值

逆波兰表达式求值

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

import java.util.*;


public class Solution {
    public int evalRPN (String[] tokens) {
        // write code here
        Stack<Integer> stack = new Stack<>();
	  	// 注意这里是要把每次的结果也一起压入栈中,继续计算
        for(String token : tokens){
            if(!token.equals("+") && !token.equals("-") && !token.equals("*") && !token.equals("/")){
                stack.push(Integer.parseInt(token));
            }else{
                int num1 = stack.pop();
                int num2 = stack.pop();
                if(token.equals("+")){
                    stack.push(num1 + num2);
                }else if(token.equals("-")){
                    stack.push(num2 - num1);
                }else if(token.equals("*")){
                    stack.push(num2 * num1);
                }else if(token.equals("/")){
                    stack.push(num2 / num1);
                }
            }
        }
        return stack.pop();
    }
}

全部评论

相关推荐

02-28 01:18
已编辑
南昌大学 后端工程师
黑皮白袜臭脚体育生:把开源经历放个人项目上边应该更好,就像大部分人都把实习经历放个人项目上边
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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