Leetcode 150. Evaluate Reverse Polish Notation
Posted Deribs4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 150. Evaluate Reverse Polish Notation相关的知识,希望对你有一定的参考价值。
Similar Questions Basic Calculator Expression Add Operators
思路:逆波兰式的计算(Reverse Polish Notation),利用栈,正向遍历String数组,遇到符号字符,就将栈顶的2个元素弹出做对应计算,将计算结果压栈;遇到数字,直接压栈。
1 class Solution { 2 public int evalRPN(String[] tokens) { 3 Stack<Integer> s = new Stack<Integer>(); 4 for(int i = 0; i < tokens.length; i++) { 5 int a, b; 6 switch(tokens[i]) { 7 case "+": 8 s.push(s.pop() + s.pop()); 9 break; 10 case "-": 11 a = s.pop(); 12 b = s.pop(); 13 s.push(b - a); 14 break; 15 case "*": 16 s.push(s.pop() * s.pop()); 17 break; 18 case "/": 19 a = s.pop(); 20 b = s.pop(); 21 s.push(b / a); 22 break; 23 default: s.push(Integer.parseInt(tokens[i])); 24 } 25 } 26 return s.pop(); 27 } 28 }
Next challenges:
以上是关于Leetcode 150. Evaluate Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode150. Evaluate Reverse Polish Notation
刷题-LeetCode150 Evaluate Reverse Polish Notation
[LeetCode] 150. Evaluate Reverse Polish Notation
[LeetCode] 150. Evaluate Reverse Polish Notation