
可以构建一个int类型的栈,在遍历token数组的时候,如果遇到数字,就把字符串类型的数字转化为int类型,放入s栈中,如果遇到加减乘除符号,就把栈顶的两个元素取出来,进行相应的运算操作,然后把计算结果压入栈中。
最后的答案就是栈顶元素,全部处理完后栈中只有一个元素。
java
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<>();
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")){
int x=stack.pop();
int y=stack.pop();
int z=x+y;
stack.push(z);
}else if(tokens[i].equals("-")){
int x=stack.pop();
int y=stack.pop();
int z=y-x;
stack.push(z);
}else if(tokens[i].equals("*")){
int x=stack.pop();
int y=stack.pop();
int z=x*y;
stack.push(z);
}else if(tokens[i].equals("/")){
int x=stack.pop();
int y=stack.pop();
int z=y/x;
stack.push(z);
}else{
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}