[Leetcode][JAVA] Evaluate Reverse Polish Notation
2014-09-10 04:45
537 查看
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 使用栈即可实现。遇到运算符号即pop出俩数运算,否则push 由于测试用例没有非法的表达式,所以很容易即可ACCEPT
public int evalRPN(String[] tokens) { Stack<String> st = new Stack<String>(); for(int i=0;i<tokens.length;i++) { String t = tokens[i]; if(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) { int x2 = Integer.parseInt(st.pop()); int x1 = Integer.parseInt(st.pop()); if (t.equals("+")) st.push(String.valueOf(x1 + x2)); else if (t.equals("-")) st.push(String.valueOf(x1 - x2)); else if (t.equals("*")) st.push(String.valueOf(x1 * x2)); else st.push(String.valueOf(x1 / x2)); } else st.push(t); } return Integer.parseInt(st.pop()); }
相关文章推荐
- 【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:Evaluate Reverse Polish Notation (Java)
- 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