首页 > 编程语言 > 详细

LeetCode150 Evaluate Reverse Polish Notation java题解

时间:2015-06-30 13:05:10      阅读:311      评论:0      收藏:0      [点我收藏+]

题目:

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
解题:

这题是栈的一个经典应用,也比较简单,思路就是:遇到数字就进栈,遇到运算符号就出栈两个数字然后再将计算结果进栈。

代码:

import java.util.Stack;


public class LeetCode150_EvaluateReversePolishNotation {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] s={"4","-2","/","2","-3","-","-"};
		System.out.println(evalRPN(s));
		

	}
	
	
	 public static int evalRPN(String[] tokens) {
		 int length=tokens.length;
		 Stack<Integer> stack =new Stack<>();
		 
		 for(int i=0;i<length;i++)
		 {
			 if(!isOperator(tokens[i]))
				 stack.push(Integer.parseInt(tokens[i]));
			 else {
				int operaNum2=stack.pop();
				int operaNum1=stack.pop();
				if(tokens[i].equals("+"))
					stack.push(operaNum1+operaNum2);
				else if(tokens[i].equals("-"))
					stack.push(operaNum1-operaNum2);
				else if(tokens[i].equals("*"))
					stack.push(operaNum1*operaNum2);
				else {
					stack.push(operaNum1/operaNum2);
				}
			}
				 
		 }
		 
		 return stack.pop();
		 
	        
	    }
	 
	 public static boolean isOperator(String s) 
	 {
		 if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/"))
			 return true;
		 else
			 return false;
	 }

}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode150 Evaluate Reverse Polish Notation java题解

原文:http://blog.csdn.net/u012249528/article/details/46692083

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