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

[leecode]Evaluate Reverse Polish Notation

2014-08-05 10:28 417 查看

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


算法思路:

很经典的stack应用,书中例题,遇到数字压栈,遇到符号弹栈,并将结果压栈,最后返回栈顶元素。

public class Solution {
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0) return 0;
String[] operand = new String[]{"+","-","*","/"};
Set<String> set = new HashSet<String>(Arrays.asList(operand));
Stack<Integer> num = new Stack<Integer>();
for(String s : tokens){
if(!set.contains(s)){
num.push(Integer.valueOf(s));
}else{
int b = num.pop();
int a = num.pop();
switch(s){
case "*": num.push(a * b); break;
case "+": num.push(a + b); break;
case "-": num.push(a - b); break;
case "/": num.push(a / b); break;
default : break;
}
}
}
return num.pop();
}
}


第二遍:

有if-else语句来代替switch,基本思想一样

public class Solution {
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0) return 0;
LinkedList<Integer> stack = new LinkedList<Integer>();
for(int i = 0; i < tokens.length; i++){
if("+".equals(tokens[i])){
int tem = stack.pop();
stack.push(stack.pop() + tem);
}else if("-".equals(tokens[i])){
int tem = stack.pop();
stack.push(stack.pop() - tem);
}else if("*".equals(tokens[i])){
int tem = stack.pop();
stack.push(stack.pop() * tem);
}else if("/".equals(tokens[i])){
int tem = stack.pop();
stack.push(stack.pop() / tem);
}else{
stack.push(Integer.valueOf(tokens[i]));
}
}
return stack.pop();
}
}


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