Use a stack to delete all redundant spaces in the original string. After pushing all characters into the stack, all words are in a reversed state. While popping, reverse every word and append them to the final result.
class Solution {
public:
void reverseWords(string &s) {
int i;
for(i=0;i<s.size();i++)
if(s[i]!=' ')
break;
s=s.substr(i);
for(i=s.size()-1;i>=0;i--)
if(s[i]!=' ')
break;
s=s.substr(0,i+1);
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i]==' '&&st.top()==' ')
continue;
st.push(s[i]);
}
string res;
string word;
while(!st.empty())
{
if(st.top()!=' ')
word+=st.top();
else
{
reverse(word.begin(),word.end());
res+=word+' ';
word.clear();
}
st.pop();
}
reverse(word.begin(),word.end());
res+=word;
s=res;
}
};