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

Evaluate Reverse Polish Notation

2015-11-04 18:03 295 查看
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

关键点:stack

思路:遇到数字则进栈,遇到操作符则取出栈顶的两个元素进行运算,要注意的是取出的元素和操作数顺序的关系。

代码:

public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
switch (tokens[i]) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
stack.push(-stack.pop() + stack.pop());
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
int n1 = stack.pop(), n2 = stack.pop();
stack.push(n2 / n1);
break;
default:
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: