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.
Idea: Using the split method of string to split, the regular expression of its segmentation is "".
1 Public classSolution {2 /**3 * @params:a String4 * @return: A string5 */6 Publicstring Reversewords (string s) {7 if(s = =NULL|| S.length () = = 0) {8 return"";9 }Tenstring[] Words = S.split (""); OneStringBuilder Builder =NewStringBuilder (); A for(inti = words.length-1; I >= 0; i--) { - if(Words[i]! = "") { -Builder.append (Words[i]). Append (""); the } - } - returnBuilder.length () = = 0? "": builder.substring (0, Builder.length ()-1); - } +}
Reverse Words in a String