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

【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值

2015-07-30 17:12 537 查看
求逆波兰表达式的值。

在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

样例

[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9

[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

说明

什么是逆波兰表达式?

http://en.wikipedia.org/wiki/Reverse_Polish_notation

public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
if(null == tokens || tokens.length == 0) return 0;
Set<String> cSet = new HashSet<String>();
cSet.add("+");
cSet.add("-");
cSet.add("*");
cSet.add("/");
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < tokens.length; i++) {
if(!cSet.contains(tokens[i])) {
stack.push(Integer.valueOf(tokens[i]));
}else {
int b = stack.pop();
int a = stack.pop();
int c = 0;
char[] arr = tokens[i].toCharArray();
switch (arr[0]){
case '+':
c = a + b;
break;
case '-':
c = a - b;
break;
case '*':
c = a * b;
break;
case '/':
c = a / b;
}
stack.push(c);
}
}
return stack.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: