Convert Expression to Reverse Polish Notation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.