Leetcode 150. Evaluate Reverse Polish Notation

Similar Questions Basic Calculator Expression Add Operatorsexpress

思路:逆波蘭式的計算(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: Expression Add Operatorside

相關文章
相關標籤/搜索