[Leetcode] [JAVA] Reverse Words in a String

Source: Internet
Author: User

Given an input string, reverse the string word by word.

For example,
Given s = " the sky is blue ",
Return " blue is sky the ".

Clarification:

What constitutes a word?

    A sequence of non-space characters constitutes a word.

Could the input string contain leading or trailing spaces?

    Yes. However, your reversed string should not contain leading or trailing spaces.

How about multiple spaces between and words?

    Reduce them to a single space in the reversed string.

There are simple ways to use Java or Python:

This is my first AC code, with the Split () method:

 Public string Reversewords (string s) {        = S.split ("");         = "";          for (int i=token.length;i>0;i--)        {            if(Token[i-1].compareto (")!=0)                = re + token[i-1] +" ";        }         return Re.trim ();    }


Later see discuss said is cheat, change to:

 Publicstring Reversewords (string s) {ArrayList<String> ls =NewArraylist<string>(); intI=0;  while(i<s.length ()) {            if(! (S.charat (i) = = "))            {                intj=i; String Temp= "";  while(J<s.length () &&! (S.charat (j) = = ") ) {temp+=S.charat (j); J++;                } ls.add (temp); I=J; }            ElseI++; } String re= "";  for(intJ=ls.size () -1;j>=0;j--) {Re= re + ls.get (j) + ""; }        returnRe.equals ("")? Re:re.substring (0,re.length ()-1); }

Scan down with non-whitespace until you encounter a space or scan to the end of the string to get a complete word.
Take a data structure (here with ArrayList) to save the intercepted word and then output it from the back.

Finally, you need to remove the possible trailing spaces.

[Leetcode] [JAVA] Reverse Words in a String

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.