首页 > 代码库 > LeetCode--Reverse Words in a String

LeetCode--Reverse Words in a String

class Solution {public:    void reverseWords(string &s) {        int len = s.length();        if(len == 0)            return;        vector<string> res;        int i = 0;        int j = len-1;        //去掉收尾的空格        while(i < len && s[i] ==  )            ++i;        while(j >= 0 && s[j] ==  )            --j;        int k = i;//寻找一个单词        while(i <= j)        {            k = i;            while(i<=j && s[i]!= )            {                ++i;            }            res.push_back(s.substr(k,i-k));            while(s[i]==  && i<=j)                ++i;        }        if(res.empty())        {            s = "";            return;        }        reverse(res.begin(),res.end());        string m = res[0];        for(int i=1;i<res.size();i++){              m+=" ";              m+=res[i];          }          s=m;     }};

先删除前后的空格,多个空格合并为一个空格输出。