目录
一、题目描述
二、思路
三、代码实现
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < tokens.length; i++){
String val = tokens[i];
if(! isOperator(val)){//不是运算符
stack.push(Integer.parseInt(val));
}else{//判断是什么运算符
int num2 = stack.pop();
int num1 = stack.pop();
switch(val){
case "+":
stack.push(num1 + num2);
break;
case "-":
stack.push(num1 - num2);
break;
case "*":
stack.push(num1 * num2);
break;
case "/":
stack.push(num1 / num2);
break;
}
}
}
return stack.pop();
}
private boolean isOperator(String x){
if(x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/")){
return true;
}
return false;
}
}