LeetCode刷题笔录Evaluate Reverse Polish Notation
2014-10-28 09:30
423 查看
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:
这题原来写计算器的时候写过。有一个stack,对于input的string检查是什么类型的:如果是数字的话就丢到stack里;如果是算符的话就从stack里pop两个数字出来进行相应的计算,再把结果push回stack里。最后返回stack顶的元素就行了。
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(); } }
相关文章推荐
- LeetCode - Evaluate Reverse Polish Notation
- 【LeetCode-面试算法经典-Java实现】【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[AC源码]
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- LeetCode – Refresh – Evaluate Reverse Polish Notation
- (leetcode)Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- 【Leetcode】Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- leetcode之Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- leetcode 刷题之路 2 Evaluate Reverse Polish Notation
- leetcode--Evaluate Reverse Polish Notation
- LeetCode::Evaluate Reverse Polish Notation
- Leetcode在线编程evaluate-reverse-polish-notation