码迷,mamicode.com
首页 > 其他好文 > 详细

Convert Expression to Reverse Polish Notation

时间:2016-07-21 12:44:15      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

Convert Expression to Reverse Polish Notation

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5691242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!