150. 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

题目含义:逆波兰计算,大话数据结构中讲到过,用一个栈来实现后缀表达式的计算。
思路:从左到右遍历表达式的每个数字和字符,遇到数字就进栈,遇到符号,就将栈顶的两个数字取出(注意第一次取出的是右操作数,第二次取出的栈顶数字是左操作数),进行运算,将运算结果压栈,一直到最终获得计算结果(最终的栈顶数字)

 1     public int evalRPN(String[] tokens) {
 2         int a,b;
 3         Stack<Integer> S = new Stack<Integer>();
 4         for (String s : tokens) {
 5             if(s.equals("+")) {
 6                 S.add(S.pop()+S.pop());
 7             }
 8             else if(s.equals("/")) {
 9                 b = S.pop();
10                 a = S.pop();
11                 S.add(a / b);
12             }
13             else if(s.equals("*")) {
14                 S.add(S.pop() * S.pop());
15             }
16             else if(s.equals("-")) {
17                 b = S.pop();
18                 a = S.pop();
19                 S.add(a - b);
20             }
21             else {
22                 S.add(Integer.parseInt(s));
23             }
24         }
25         return S.pop();        
26     }

 

 

 

 

 
posted @ 2017-10-25 10:24  daniel456  阅读(127)  评论(0编辑  收藏  举报