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 classSolution {2 /**3 * @param expression:a string array4 * @return: The Reverse Polish notation of this expression5 */6 PublicArraylist<string>CONVERTTORPN (string[] expression) {7arraylist<string> list =NewArraylist<string>();8stack<string> stack =NewStack<string>();9 Ten for(inti =0; i < expression.length; i++) { OneString str =Expression[i]; A if(Isoperator (str)) { - if(Str.equals ("(")) { - Stack.push (str); the}Else if(Str.equals (")")) { - while(!stack.isempty () &&!stack.peek (). Equals ("(")) { - List.add (Stack.pop ()); - } + Stack.pop (); -}Else { + while(!stack.isempty () && order (str) <=Order (Stack.peek ())) { A List.add (Stack.pop ()); at } - Stack.push (str); - } -}Else { - List.add (str); - } in } - while(!Stack.isempty ()) { to List.add (Stack.pop ()); + } - returnlist; the } * $ Privateboolean isoperator (String str) {Panax Notoginseng if(Str.equals ("+") || Str.equals ("-") || Str.equals ("*") || Str.equals ("/") || Str.equals ("(") -|| Str.equals (")")) { the return true; + } A return false; the } + - Private intorder (String a) { $ if(A.equals ("*") || A.equals ("/")) { $ return 2; -}Else if(A.equals ("+") || A.equals ("-")) { - return 1; the}Else { - return 0;Wuyi } the } -}
Convert Expression to Reverse Polish Notation