Convert Expression to Reverse Polish Notation

Given an expression string array, return the Reverse Polish notation of this expression. (remove the parentheses)

Example

For the expression [3 - 4 + 5] (which denote by ["3", "-", "4", "+", "5"]), return [3 4 - 5 +] (which denote by ["3", "4", "-", "5", "+"])

 1 public class Solution {
 2     public List<String> convertToRPN(String[] expression) {
 3         List<String> list = new ArrayList<>();
 4         Stack<String> stack = new Stack<>();
 5 
 6         for (String str : expression) {
 7             if (isOperator(str)) {
 8                 if (str.equals("(")) {
 9                     stack.push(str);
10                 } else if (str.equals(")")) {
11                     while (!stack.isEmpty() && !stack.peek().equals("(")) {
12                         list.add(stack.pop());
13                     }
14                     stack.pop();
15                 } else {
16                     while (!stack.isEmpty() && order(str) <= order(stack.peek())) {
17                         list.add(stack.pop());
18                     }
19                     stack.push(str);
20                 }
21             } else {
22                 list.add(str);
23             }
24         }
25         while (!stack.isEmpty()) {
26             list.add(stack.pop());
27         }
28         return list;
29     }
30 
31     private boolean isOperator(String str) {
32         if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") || str.equals("(")
33                 || str.equals(")")) {
34             return true;
35         }
36         return false;
37     }
38 
39     private int order(String a) {
40         if (a.equals("*") || a.equals("/")) {
41             return 2;
42         } else if (a.equals("+") || a.equals("-")) {
43             return 1;
44         } else {
45             return 0;
46         }
47     }
48 }

相关问题:Evaluate Reverse Polish Notation ( https://www.cnblogs.com/beiyeqingteng/p/5679265.html )

posted @ 2016-07-21 11:52  北叶青藤  阅读(299)  评论(0编辑  收藏  举报