Given an input string, reverse the string word by word.
Example 1:
Input: “the sky is blue”
Output: “blue is sky the”
Example 2:
Input: " hello world! "
Output: “world! hello”
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: “a good example”
Output: “example good a”
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
C++
string reverseWords(string s) {
reverse(s.begin(),s.end());
int len = s.size();
int index = 0;
for(int i = 0;i < len;++i)
{
if(s[i] != ' ')
{
if(index != 0)s[index++] = ' ';
int j = i;
while(j < len&&s[j] != ' ')s[index++] = s[j++];
reverse(s.begin() + index - (j - i),s.begin() + index);
i = j;
}
}
s.resize(index);
return s;
}