您的位置:首页 > 编程语言 > Lua

LeetCode 2 Evaluate Reverse Polish Notation

2014-08-18 16:42 246 查看
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 Solution {    public int evalRPN(String[] tokens) {		Deque<Integer> stack = new ArrayDeque<Integer>();		for (int i = 0; i < tokens.length; i++) {			if ((tokens[i].charAt(0) >= '0' && tokens[i].charAt(0) <= '9')					|| (tokens[i].charAt(0) == '-' && tokens[i].length() > 1)) {				stack.push(Integer.parseInt(tokens[i]));			} else {				int x = stack.pop();				int y = stack.pop();				switch (tokens[i].charAt(0)) {				case '+':					stack.push(y + x);					break;				case '-':					stack.push(y - x);					break;				case '*':					stack.push(y * x);					break;				case '/':					stack.push(y / x);					break;				default:					break;				}			}		}		return stack.pop();	}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: