LeetCode Evaluate Reverse Polish Notation(用栈来计算后缀表达式)
2014-05-01 09:15
519 查看
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:
public class Solution {
public int evalRPN(String[] tokens) {
String operators = "+-*/";
int result = 0;
Stack<String> stack = new Stack<String>();
for (String s: tokens) {
if (!operators.contains(s)) {
stack.push(s);
} else {
int b = Integer.valueOf(stack.pop());
int a = Integer.valueOf(stack.pop());
switch (s) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(a - b));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(a / b));
break;
}
}
}
result = Integer.valueOf(stack.pop());
return result;
}
}
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) {
String operators = "+-*/";
int result = 0;
Stack<String> stack = new Stack<String>();
for (String s: tokens) {
if (!operators.contains(s)) {
stack.push(s);
} else {
int b = Integer.valueOf(stack.pop());
int a = Integer.valueOf(stack.pop());
switch (s) {
case "+":
stack.push(String.valueOf(a + b));
break;
case "-":
stack.push(String.valueOf(a - b));
break;
case "*":
stack.push(String.valueOf(a * b));
break;
case "/":
stack.push(String.valueOf(a / b));
break;
}
}
}
result = Integer.valueOf(stack.pop());
return result;
}
}
相关文章推荐
- LeetCode 150. Evaluate Reverse Polish Notation(计算后缀表达式)
- [LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
- Leetcode (10) Evaluate Reverse Polish Notation (计算逆波兰表示法多项式)
- 【LeetCode刷题Java版】Evaluate Reverse Polish Notation(计算逆波兰表达式)
- 【leetcode】Evaluate Reverse Polish Notation 计算后缀表达式的值(JAVA)
- Leetcode刷题记——150. Evaluate Reverse Polish Notation(计算逆波兰表达式)
- Leetcode 150:Evaluate Reverse Polish Notation(计算逆波兰表达式) --java实现
- 【LeetCode-面试算法经典-Java实现】【150-Evaluate Reverse Polish Notation(计算逆波兰式)】
- leetcode Evaluate Reverse Polish Notation(计算逆波兰表达式)
- [Leetcode] evaluate reverse polish notation 计算逆波兰表达式
- 【LeetCode-面试算法经典-Java实现】【151-Evaluate Reverse Polish Notation(计算逆波兰式)】
- leetcode笔记:Evaluate Reverse Polish Notation(逆波兰式的计算)
- [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)
- 每日AC - 后缀表达式计算结果-leetcode-evaluate-reverse-polish-notation
- Evaluate Reverse Polish Notation - LeetCode 150
- LeetCode 150 — Evaluate Reverse Polish Notation(C++ Java Python)
- Leetcode Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- Leetcode#150 Evaluate Reverse Polish Notation
- 【leetcode刷题笔记】Evaluate Reverse Polish Notation