首页 > 代码库 > LeetCode 2 Evaluate Reverse Polish Notation

LeetCode 2 Evaluate Reverse Polish Notation

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();
	}
}