leetcode #151 in cpp

本文介绍了一种通过两次反转实现字符串单词顺序反转的方法,并去除了单词间的多余空格。

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

Solution:

1. reversed the whole string

2. reversed each word in the reversed string.

3. remove multiple space between words. 

Code:

class Solution {
public:
    void reverseWords(string &s) {
        if(s.empty()) return; 
        int head = 0;
        int end = s.length() -1;
        char temp;
        //reverse the string
        while(head<end){
            temp = s[head];
            s[head]= s[end];
            s[end] = temp;
            head++;
            end --;
        }
        
        head = 0;
        int temp_end;
        //reverse each word in the reversed string
        while(true){
            while(head < s.length() && s[head] == ' '){
                head++; 
            }
            if(head >= s.length()) break;
            end = head;
            while(end < s.length() && s[end] != ' '){
                end++; 
            }
            end --; 
            temp_end = end; 
            while(head<end){
                temp = s[head];
                s[head] = s[end];
                s[end] = temp;
                head++;
                end--;
            }
            head = temp_end + 1; 
        }
        
        int cur = 0;
        head = 0;
        //reduce multiple " " between word. 
        while(head<s.length()){
            if(s[head] != ' '){//move word to s[cur]. This step ensures that there are no multiple                    //spaces between words. 
                s[cur++] = s[head++];
            }
            else{//if we meet a " " at s[head],first find the next word
                while(head < s.length() && s[head] == ' '){
                    head++;
                }
                if(head >= s.length()) break;
                if(cur > 0){//if cur > 0, first append a " " at s[cur]. then append the word
                    s[cur] = ' ';
                    cur++;
                }
            }
        }
        s = s.substr(0,cur);
        
    }
   
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值