LeetCode:Evaluate Reverse Polish Notation (Java)
2014-08-06 01:09
573 查看
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression inReverse 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 { private Set<String> set = new HashSet<String>(); { //初始化块 set.add("+"); set.add("-"); set.add("*"); set.add("/"); } public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); int num1,num2 = 0; for(int i=0;i<tokens.length;i++) { if(!set.contains(tokens[i])) { stack.push(Integer.parseInt(tokens[i])); } else { num2 = stack.pop(); num1 = stack.pop(); stack.push(calculate(tokens[i].charAt(0), num1, num2)); } } return stack.pop(); } private int calculate(char operator, int num1, int num2) { switch(operator) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': return num1 / num2; default: return 0; } } }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【151-Evaluate Reverse Polish Notation(计算逆波兰式)】
- 【LeetCode-面试算法经典-Java实现】【150-Evaluate Reverse Polish Notation(计算逆波兰式)】
- Leetcode 150:Evaluate Reverse Polish Notation(计算逆波兰表达式) --java实现
- LeetCode 150 — Evaluate Reverse Polish Notation(C++ Java Python)
- 【LeetCode刷题Java版】Evaluate Reverse Polish Notation(计算逆波兰表达式)
- 【leetcode】Evaluate Reverse Polish Notation 计算后缀表达式的值(JAVA)
- [Leetcode][JAVA] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation leetcode java
- LeetCode 150. Evaluate Reverse Polish Notation(java)
- Leetcode-Evaluate Reverse Polish Notation-java
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- [Leetcode] Evaluate Reverse Polish Notation (Java)
- Java for LeetCode 150 Evaluate Reverse Polish Notation
- 【Leetcode】Evaluate Reverse Polish Notation JAVA
- Evaluate Reverse Polish Notation leetcode java
- Leetcode: Evaluate Reverse Polish Notation (Java)
- python整除问题-leetcode-Evaluate Reverse Polish Notation
- LeetCode: Evaluate Reverse Polish Notation
- 天天LeetCode之Evaluate Reverse Polish Notation
- [leetcode]Evaluate Reverse Polish Notation