Leetcode: Evaluate Reverse Polish Notation
2014-11-08 13:32
405 查看
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:
Use stack.
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (tokens[i].equals("-")) {
stack.push(-stack.pop() + stack.pop());
} else if (tokens[i].equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (tokens[i].equals("/")) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 / num2);
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
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
Use stack.
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (tokens[i].equals("-")) {
stack.push(-stack.pop() + stack.pop());
} else if (tokens[i].equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (tokens[i].equals("/")) {
int num2 = stack.pop();
int num1 = stack.pop();
stack.push(num1 / num2);
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}
相关文章推荐
- [LeetCode] Evaluate Reverse Polish Notation
- leetcode_Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- [LeetCode]150. Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation (Java)
- leetcode--evaluate-reverse-polish-notation
- LeetCode-Evaluate Reverse Polish Notation
- leetcode笔记:Evaluate Reverse Polish Notation(逆波兰式的计算)
- LeetCode第一题:Evaluate Reverse Polish Notation
- Java for LeetCode 150 Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- Leetcode刷题记——150. Evaluate Reverse Polish Notation(计算逆波兰表达式)
- (leetcode)Evaluate Reverse Polish Notation
- leetcode 150.Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation, Solution
- Leetcode 之Evaluate Reverse Polish Notation(41)
- leetcode-Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation