Given an input string, reverse the string word by word.
For example,
Given S ="the sky is blue
",
Return"blue is sky the
".
Click to show clarification.
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.
Train of Thought: scan the string from the beginning to the end, not from the space. Put the word into temp until there is a space. Put the word into result as follows. Then, put the word in front of the previous word and add a space. In this way, words and words can be reversed.
class Solution {public: void reverseWords(string &s) { int nLen=s.size(); if(nLen<=0) return; string temp,result; int index=0; while(s[index]==‘ ‘) index++; for(int i=index;i<nLen;) { if(s[i]!=‘ ‘) { temp+=s[i]; i++; } else { while(s[i]==‘ ‘) i++; if(i==nLen) break; result=" "+temp+result; temp=""; } } s=temp+result; }};