根据 逆波兰表示法,求表达式的值。 有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 说明: 整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。 示例 1: 输入:tokens = ["2","1","+","3","*"] 输出:9 解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9 示例 2: 输入:tokens = ["4","13","5","/","+"] 输出:6 解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
很简单,跟前几道一模一样
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack();
for(String s:tokens){
if(s.equals("+")){
int a=stack.pop();
int b=stack.pop();
stack.push(b+a);
}else if(s.equals("*")){
int a=stack.pop();
int b=stack.pop();
stack.push(b*a);
}else if(s.equals("-")){
int a=stack.pop();
int b=stack.pop();
stack.push(b-a);
}else if(s.equals("/")){
int a=stack.pop();
int b=stack.pop();
stack.push(b/a);
}else {
stack.push(Integer.parseInt(s));
}
}
if(!stack.isEmpty()){
return stack.peek();
}
return 0;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有