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

【LeetCode】Evaluate Reverse Polish Notation

2014-05-04 11:12 417 查看
题目

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) {
if(tokens==null||tokens.length==0) return 0;
Stack<Integer> s=new Stack<Integer>();
int num1,num2;
for(int i=0;i<tokens.length;i++){
String ch=tokens[i];
if(!(ch.equals("+")||ch.equals("-")||ch.equals("*")||ch.equals("/"))){ //注意是||,不是&&
s.push(Integer.valueOf(ch));
}else{
num1=s.pop();
num2=s.pop();
if(ch.equals("+")){
s.push(num2+num1);
}else if(ch.equals("-")){
s.push(num2-num1);
}else if(ch.equals("*")){
s.push(num2*num1);
}else{
s.push(num2/num1);
}
}
}
return s.pop();
}
}
---EOF---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: