Valid operators are +, -, *, /. Each operand may be an integer or another expression.
public class Solution {
public int evalRPN(String[] tokens) {
int result=0;
List<Integer> arrayList=new LinkedList<Integer>();
int temp1=0;
int temp2=0;
for(String temp:tokens){
if(temp.compareTo("+")==0){
temp1=arrayList.remove(arrayList.size()-1);
temp2=arrayList.remove(arrayList.size()-1);
result=temp2+temp1;
arrayList.add(arrayList.size(),result);
}
else if(temp.compareTo("-")==0){
temp1=arrayList.remove(arrayList.size()-1);
temp2=arrayList.remove(arrayList.size()-1);
result=temp2-temp1;
arrayList.add(arrayList.size(),result);
}else if(temp.compareTo("*")==0){
temp1=arrayList.remove(arrayList.size()-1);
temp2=arrayList.remove(arrayList.size()-1);
result=temp2*temp1;
arrayList.add(arrayList.size(),result);
}else if(temp.compareTo("/")==0){
temp1=arrayList.remove(arrayList.size()-1);
temp2=arrayList.remove(arrayList.size()-1);
result=temp2/temp1;
arrayList.add(arrayList.size(),result);
}else{
arrayList.add(arrayList.size(),Integer.parseInt(temp));
}
}
result=arrayList.get(0);
return result;
}
}
思路:将数组中的内容遍历,遇见数字就存入list中,遇见符号就弹出,将计算的结果再存入list中。
一开始用temp==“/”老是报runtime error 。换成temp.compareTo("/")==0就Accepted了
本文介绍了一种解决逆波兰表示法(RPN)表达式的算法实现。通过使用List存储中间结果,遇到运算符时从List中取出两个操作数进行计算,并将结果重新放入List中,最终List中仅剩的元素即为表达式的计算结果。
210

被折叠的 条评论
为什么被折叠?



