Leetcode - string - Reverse Words in a String

来源:互联网 发布:男士 爽肤水 知乎 混合 编辑:程序博客网 时间:2024/05/21 14:07
class Solution {public:    void reverseWords(string &s) {        istringstream record(s);        string temp;        vector<string> vec;        while(record>>temp)        {            vec.push_back(temp);        }        int theSize=vec.size();        s="";        for(auto i=theSize-1;i>=0;i--)        {            s=s+vec[i];            if(i!=0)            s=s+" ";        }    }};


不使用vector,直接使用istringstream来解决

/** * 1.s is empty. * 2.s is spaces. * 3.s ends or begins with spaces. */class Solution {public:    void reverseWords(string &s) {        if(s.empty())            return;        istringstream record(s);        string str;        s.clear();        while(record>>str)        {            s=str+' '+s;        }        if(!s.empty())            s.erase(s.end()-1);    }};


0 0
原创粉丝点击