码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 150] Evaluate Reverse Polish Notation

时间:2015-03-28 15:51:06      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   算法   

题目链接:evaluate-reverse-polish-notation


import java.util.Stack;

/**
 * 
		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
 *
 */

public class EvaluateReversePolishNotation {

	
//	20 / 20 test cases passed.
//	Status: Accepted
//	Runtime: 346 ms
//	Submitted: 0 minutes ago

	//时间复杂度O(n) 空间复杂度O(n)
    public int evalRPN(String[] tokens) {
        
    	Stack<Integer> stack = new Stack<Integer>();
        for (String s : tokens) {
			if(isOp(s)) {
				stack.push(operation(stack.pop(), s, stack.pop()));
			} else {
				stack.push(stringToInt(s));
			}
		}
    	return stack.pop();
    }
    
    //判断是否为操作符
    public boolean isOp(String s) {
    	if(s.equals("+")
    		||s.equals("-")
    		||s.equals("*")
    		||s.equals("/")) {
    		return true;
    	} else {
			return false;
		}
    }
    
    //对两个数进行运算符操作
    public int operation(int b, String s, int a) {
    	if(s.equals("+"))
    		return a + b;
    	else if(s.equals("-"))
    		return a - b;
    	else if(s.equals("*"))
    		return a * b;
    	else
    		return a / b;
    }
    
    //将数字字符串转化成数字
    public int stringToInt(String s) {
    	int n = 0;
    	int flag = 1;
    	for (Character c : s.toCharArray()) {
			//判断是否为负数
    		if(c == '-') {
				flag = -1;
				continue;
			}
			n = 10 * n + c - '0';
		}
    	return flag * n;
    }
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


[LeetCode 150] Evaluate Reverse Polish Notation

标签:java   leetcode   算法   

原文地址:http://blog.csdn.net/ever223/article/details/44701279

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!