4.Reverse Words in a String-Leetcode

class Solution {
public:
    void reverseWords(string &s) {
 vector<string> data;
        string word;
        stringstream ss(s);
        while(ss>>word) data.push_back(word);

        vector<string> rdata(data.rbegin(), data.rend());

        s = accumulate(rdata.begin(), rdata.end(), string(""),
            [](string s1, string s2){
                if(s1.empty()) return s2;
                else return s1+" "+s2; 
            });

    }
};

class Solution {
public:
    void reverseWords(string &s) {
        for(string::size_type ix=0;ix!=s.size();++ix)
        {
            if(s[ix]==' ')
                if(s[ix+1]==' '){
                    s.erase(ix,1);
                    ix--;
                }       
        }
        if(s[0]==' ')s.erase(0,1);
        if(s[s.size()-1]==' ')s.erase(s.size()-1,1);
        int k=0;
        string st(s.size(),'a');
        for(string::size_type ix=s.size()-1;ix!=-1;--ix)//全倒置 
        {
            st[k++]=s[ix];
        }
        int beg=0,end=0,n=st.size();
        int index=0;
        while(end<=n)
        {
            while(st[end]!=' '&&end<n)end++;
            for(int i=end-1;i>=beg;--i)s[index++]=st[i];
            if(st[end]==' ')s[index++]=' ';
            end=end+1;
            beg=end;
        }       
    }
};

你可能感兴趣的:(4.Reverse Words in a String-Leetcode)