[leecode]Evaluate Reverse Polish Notation
2014-08-05 10:28
417 查看
Evaluate Reverse Polish Notation
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
算法思路:
很经典的stack应用,书中例题,遇到数字压栈,遇到符号弹栈,并将结果压栈,最后返回栈顶元素。
public class Solution { public int evalRPN(String[] tokens) { if(tokens == null || tokens.length == 0) return 0; String[] operand = new String[]{"+","-","*","/"}; Set<String> set = new HashSet<String>(Arrays.asList(operand)); Stack<Integer> num = new Stack<Integer>(); for(String s : tokens){ if(!set.contains(s)){ num.push(Integer.valueOf(s)); }else{ int b = num.pop(); int a = num.pop(); switch(s){ case "*": num.push(a * b); break; case "+": num.push(a + b); break; case "-": num.push(a - b); break; case "/": num.push(a / b); break; default : break; } } } return num.pop(); } }
第二遍:
有if-else语句来代替switch,基本思想一样
public class Solution { public int evalRPN(String[] tokens) { if(tokens == null || tokens.length == 0) return 0; LinkedList<Integer> stack = new LinkedList<Integer>(); for(int i = 0; i < tokens.length; i++){ if("+".equals(tokens[i])){ int tem = stack.pop(); stack.push(stack.pop() + tem); }else if("-".equals(tokens[i])){ int tem = stack.pop(); stack.push(stack.pop() - tem); }else if("*".equals(tokens[i])){ int tem = stack.pop(); stack.push(stack.pop() * tem); }else if("/".equals(tokens[i])){ int tem = stack.pop(); stack.push(stack.pop() / tem); }else{ stack.push(Integer.valueOf(tokens[i])); } } return stack.pop(); } }
View Code
相关文章推荐
- *Evaluate Reverse Polish Notation
- LeetCode- Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation(Leetcode)
- Leetcode Evaluate Reverse Polish Notation
- [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
- evaluate-reverse-polish-notation(逆波兰表示求值)
- [LeetCode]Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation
- 150. Evaluate Reverse Polish Notation
- evaluate-reverse-polish-notation
- [LeetCode] Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- leetcode 144: Evaluate Reverse Polish Notation