Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words are always separated by a single space.

For example,
Given s = "the sky is blue",
return "blue is sky the".

Could you do it in-place without allocating extra space?

 

class Solution {
public:
//无需额外空间开销
//反转整个字符串, 再反转每个单词
void reverseWords(string &s) {
    if(s.length()<1)return;
    int i=0,j=s.length()-1;
    //去开头结尾的空格
        while(s[i]==' '&&i<s.length())
        {
            i++;
            if(i==s.length())
            {
                s="";
                return;
            }
        }
        while(s[j]==' '&&j>=0)
        {
            j--;
            if(j<0)
            {
                s="";
                return;
            }
        }
        if(j-i<0)return;
        //截取除去开头结尾空格后的部分,并将其反转
        s=s.substr(i,j-i+1);
        reverse(s.begin(),s.end());
        //对每个以空格隔开的单词再次反转
    i=0,j=0;
    while(j<s.length())
    {
        while(s[j]!=' '&&j<s.length())j++;
        reverse(s.begin()+i,s.begin()+j);
        int tmp=j;
        while(s[j]==' '&&j<s.length())j++;
        if(tmp+1<s.length())s.erase(s.begin()+tmp+1,s.begin()+j);
        //注意此时s的长度已经变短,下边需要减去相应差值
        int shortL=j-tmp-1;
        j-=shortL;
        i=j;
    }
    return;
}
/**
需额外空间开销
void reverseWords(string &s) {
    if(s.empty())return;
    string tmp="";
    string str="";
    int i=0;
    while(i<s.length())
    {
        while(s[i]==' '&&i<s.length())i++;
        if(s[i]!=' '&&i<s.length())
        {
            while(s[i]!=' '&&i<s.length())tmp=s[i++]+tmp;
            str+=(tmp+' ');
            tmp="";
        }
    }
    reverse(str.begin(),str.end());
    int n=str[0]==' '?1:0;
    s=str.substr(n,str.size());
    return;
}
*/
};