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 ".

Has you met this question in a real interview?Yes 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.
Analysis: Remove the extra white space first, then the conversion (a^tb^t) ^t = ba.
1  Public classSolution {2     /**3 * @param s:a string4 * @return: A string5      */6      Publicstring Reversewords (string s) {7         if(s = =NULL|| S.length () <=1)returns;8 9         intStart =0;Tenlist<character> list =NewArraylist<character>(); Ones =S.trim (); A  -          for(inti =0; I < s.length (); i++) { -             if(! (S.charat (i) = =' '&& list.Get(List.size ()-1) ==' ')) { the List.add (S.charat (i)); -             } -         } -  +          for(inti =0; I < list.size (); i++) { -             if(list.Get(i) = =' ') { +Swap (list, start, I-1); AStart = i +1; at             } -         } -  -Swap (list, start, list.size ()-1); -Swap (list,0, List.size ()-1); -  inStringBuilder SB =NewStringBuilder (); -          for(inti =0; I < list.size (); i++) { toSb.append (list.Get(i)); +         } -         returnsb.tostring (); the     } *  $      Public voidSwap (list<character> List,intIintj) {Panax Notoginseng          while(I <j) { -             Chartemp = list.Get(i); theList.Set(I, list.)Get(j)); +List.Set(J, temp); Ai++; thej--; +         } -     } $}

 

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.