看到这个题有点亲切啊,17年华为java实习生笔试题做过一次,后来网易笔试题又做过一次。。。。。。
只要了解后缀表达式的原理其实很简单,具体的话就自行百度吧,我直接放上代码。
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++){
String current = tokens[i];
if (current.equals("+")){
stack.push(stack.pop() + stack.pop());
}else if (current.equals("-")){
int second = stack.pop();
int first = stack.pop();
stack.push(first - second);
}else if (current.equals("*")){
stack.push(stack.pop() * stack.pop());
}else if (current.equals("/")){
int second = stack.pop();
int first = stack.pop();
stack.push(first / second);
}else {
stack.push(Integer.parseInt(current));
}
}
return stack.pop();
}
}