首页 > 其他 > 详细

leetcode-Evaluate Reverse Polish Notation

时间:2015-01-22 02:13:25      阅读:258      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!