一看就懂,用的栈,表达式求值的经典套路
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> numStack=new Stack<>();
for (String token : tokens) {
if (!isOperator(token)){
numStack.push(Integer.parseInt(token));
}else {
numStack.push(Operation(numStack.pop(),numStack.pop(),token.charAt(0)));
}
}
return numStack.pop();
}
private boolean isOperator(String token) {
if (token.length()>1){
return false;
}
char first=token.charAt(0);
return first=='+'||first=='-'||first=='*'||first=='/';
}
private int Operation(int one,int two,char token) {
switch (token){
case '+':
return one+two;
case '-':
return two-one;
case '*':
return one*two;
case '/':
return two/one;
}
return 0;
}
}