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 }
时间: 2024-11-03 05:31:28