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