Reverse Words in a String

本文介绍了一种处理输入字符串中单词顺序的方法,包括对首尾空格和连续空格的处理,通过在字符串首部插入空格简化操作流程,并采用栈数据结构实现单词的逆序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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


 

思路:就是对首尾空格和中间连续空格的处理。为了方便处理,在s的首部用insert(迭代器,要插入的值)一个空格。

从后往前来,每次发现一个单词,就逆序放到stack中,然后发现一个空格(该空格的前一个字符不能是空格),就把stack中的值挨个放到string res中。最后清空s,把res赋值给s即可。

代码:

class Solution {
public:
    void reverseWords(string &s) {
        if(s=="") return;
        string res;
        stack<char> temp;
        int i=s.size()-1;
        bool tailspace=true;
        if(s[0]!=' ') s.insert(s.begin(),' ');
        
        while(i>=0){
            if(s[i]==' '&&tailspace){
                --i;
                continue;
            }
            else if(s[i]!=' '){
                tailspace=false;
                temp.push(s[i]);
            }
            else if(s[i]==' '&&!tailspace){
                if(i!=0&&s[i-1]!=' ')
                {
                    while(!temp.empty())
                    {
                        char t=temp.top();
                        temp.pop();
                        res.push_back(t);
                    }
                    res.push_back(' ');
                }else if(i==0){//第一个字符一定是空格
                    while(!temp.empty())
                    {
                        char t=temp.top();
                        temp.pop();
                        res.push_back(t);
                    }
                }
            }
            --i;
        }
        s.clear();
        s=res;
    }
};

 

转载于:https://www.cnblogs.com/fightformylife/p/4085696.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值