leetcode151.翻转字符串里面的单词

一、题目

 

 二、代码

class Solution {
public:
    string reverseWords(string s) {
        int count = 0;
        string result;
        string s_expand = ' '+s;
        int i = s_expand.size()-1;
        while(i>=0){
            count = 0;
            while(i>=0 && s_expand[i]==' ') --i;
            while(i>=0 && s_expand[i]!=' '){
                i--;
                count++;
            }
            if(count)
                result = result + s_expand.substr(i+1,count) + ' ';
        }
        return result.substr(0, result.length()-1);
    }
};

 

posted @ 2021-12-06 16:04  星光夜  阅读(24)  评论(0编辑  收藏  举报