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

Solution1: Do not use any functiion

Yesterday Expedia interviewed himself to understand the test instructions wrong, not after the depressed unceasingly. Today re-done again, found that if the restrictions of various function, many corner case to consider, change to spend a long time. So yesterday did not have their own strength caused by nothing to complain about.

Idea: Read with stack, hit the number of space output stack, use StringBuilder to connect the letters together. But there are a lot of cornercase, such as "a", so use prev= ' to record whether you have encountered a space before. If you read a new letter again, change the prev to any other number to distinguish it from the space. After the end of the loop, empty the stack and then decide if "a" will appear, and then empty the last space. Feel like doing a lot of trouble.

 Public classSolution { Publicstring Reversewords (string s) {Stack<Character> res=NewStack<character>(); StringBuilder SB=NewStringBuilder (); CharPrev= ";  for(intI=s.length () -1;i>=0;i--)        {            if(S.charat (i)! = ") {Res.push (S.charat (i)); }            Else            {                 while(!Res.isempty ())                     {Sb.append (Res.pop ()); Prev=0; }                if(prev!= ' &&i!=0) {sb.append (" "); } prev= ' '; }        }         while(!Res.isempty ())        {Sb.append (Res.pop ()); }        if(Sb.length () >0&&sb.charat (Sb.length ()-1) = = ") {Sb.deletecharat (Sb.length ()-1); }        returnsb.tostring (); }}

Solution2:

Other use function after doing it, it will be much easier. This essay is not expected to meet again.

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