151. Reverse Words in a String

本文介绍了一种使用C++实现的字符串单词反转算法。通过巧妙地利用双层循环结构,该算法可以有效地去除输入字符串中的多余空格,并按单词单位进行反转。例如,将theskyisblue转换为blue issky the。

Given an input string, reverse the string word by word.

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

小trick:在for循环里,添加while循环。

class Solution {
public:
    void reverseWords(string &s) 
    {
        //从前往后扫描 
        string res, word;
        for(int i = s.size()-1; i >= 0;)
        {
            while(i >= 0 && s[i] == ' ')--i;//去掉空格
            if(i < 0)break;
            if(res.size() != 0)res.push_back(' ');
            word.clear();
            while(i >= 0 && s[i] != ' ')word.push_back(s[i--]);//word为找到的一个单词
            for(int j = word.size()-1; j >= 0; --j)
                res.push_back(word[j]);
        }
        s = res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值