1、前言

2、思路
遇到数字就入栈,遇到符号就出栈,然后将结果入栈
3、代码
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for(String token : tokens){
if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")){
int num1 = Integer.parseInt(stack.pop()), num2 = Integer.parseInt(stack.pop());
if(token.equals("+")){
stack.push((num2 + num1) + "");
}
if(token.equals("-")){
stack.push((num2 - num1) + "");
}
if(token.equals("*")){
stack.push((num2 * num1) + "");
}
if(token.equals("/")){
stack.push((num2 / num1) + "");
}
}else{
stack.push(token);
}
}
return Integer.parseInt(stack.pop());
}
}
网友评论