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了
leetcode-Evaluate Reverse Polish Notation
原文:http://zzcjobstudy.iteye.com/blog/2177982