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

LeetCode刷题笔录Evaluate Reverse Polish Notation

2014-10-28 09:30 393 查看
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,对于input的string检查是什么类型的:如果是数字的话就丢到stack里;如果是算符的话就从stack里pop两个数字出来进行相应的计算,再把结果push回stack里。最后返回stack顶的元素就行了。

public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> nums = new Stack<Integer>();

for(String token : tokens){
if(token.length() > 1 || (token.charAt(0) <= '9' && token.charAt(0) >= '0')){
nums.push(Integer.parseInt(token));
}
else{
int num1 = nums.pop();
int num2 = nums.pop();
switch (token.charAt(0)){
case '+':
nums.push(num1 + num2);
break;
case '-':
nums.push(num2 - num1);
break;
case '*':
nums.push(num2 * num1);
break;
case '/':
nums.push(num2 / num1);
break;
}
}
}
return nums.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: