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.
Cocould the input string contain leading or trailing spaces?
Yes. However, your reversed string shocould not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Chinese: given an input string, it is reversed by words.
For example:
Given S = "the sky is blue ",
Return "Blue is sky"
Note: What constitutes a word?
A non-empty Character Sequence forms a word.
Can the entered string contain spaces at the beginning or end?
Yes. However, your inverted string should not contain leading and trailing spaces.
What if there are multiple spaces between two words?
Reduce them into a space in the reversed string.
This question is simpler than trim. We mainly consider using spaces for cutting and space removal.
Java:
public String reverseWords(String s) { if(s.trim() == "") return null; String str[] = s.trim().split("\\s+"); StringBuilder sb = new StringBuilder(); int len = str.length; for(int i=len-1;i>=0;i--){ if(str[i] == " ") continue; sb.append(str[i]+" "); } return sb.toString().trim(); }