LeetCode 2 Evaluate Reverse Polish Notation
2014-08-18 16:42
246 查看
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
解析,利用栈结构,正确解析后缀表达式的顺序,应该是从左到直右扫描之后,在进行计算时,计算的次序于原来后缀表达式的次序相同,否则会发现除以零的错误!
public class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack = new ArrayDeque<Integer>(); for (int i = 0; i < tokens.length; i++) { if ((tokens[i].charAt(0) >= '0' && tokens[i].charAt(0) <= '9') || (tokens[i].charAt(0) == '-' && tokens[i].length() > 1)) { stack.push(Integer.parseInt(tokens[i])); } else { int x = stack.pop(); int y = stack.pop(); switch (tokens[i].charAt(0)) { case '+': stack.push(y + x); break; case '-': stack.push(y - x); break; case '*': stack.push(y * x); break; case '/': stack.push(y / x); break; default: break; } } } return stack.pop(); }}
相关文章推荐
- [LeetCode] 150. Evaluate Reverse Polish Notation
- leetcode之Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation, Solution
- LeetCode_Stack_Evaluate Reverse Polish Notation
- Leetcode - Evaluate Reverse Polish Notation
- leetcode150 Evaluate Reverse Polish Notation
- [LeetCode] evaluate-reverse-polish-notation
- [Leetcode][JAVA] Evaluate Reverse Polish Notation
- leetcode day1 -- Reverse Words in a String && Evaluate Reverse Polish Notation && Max Points on a Li
- 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 with Python】 Evaluate Reverse Polish Notation
- LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation
- python整除问题-leetcode-Evaluate Reverse Polish Notation
- LeetCode::Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation
- leetcode--Evaluate Reverse Polish Notation