LeetCode 151. Reverse Words in a String

本文详细介绍了如何使用C++实现输入字符串的高效单词级反转功能,包括去除多余空格、处理特殊字符等关键步骤,并通过实例代码演示了整个过程。

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

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



#### seems like my code currently couldn't handle the "  " case.....hmmm....

#include <string>
#include <iostream>
using namespace std;

// Let's first assume that there is no extra space.
void reverseWord(string& s, int i, int j) {
    while(i < j) {
        swap(s[i], s[j]);
        i++;
        j--;
    }
}

// secondly, we can add extra space before or after.
void removeSpaces(string& s) {
    int i = 0, j = 0, spaceCount = 0;
    while(i < s.size()) {
        if(s[i] == ' ') {
            i++;
            spaceCount++;
        } else {
            if(spaceCount >= 1) {
                s[j++] = ' ';
                spaceCount = 0;
            }
            s[j++] = s[i++];
        }
    }
    s[j] = '\0';
    if(s[0] == ' ') s = s.substr(1, j - 1);
}

void reverseWords(string& s) {
    if(s.size() <= 1) return;
    removeSpaces(s);
    reverseWord(s, 0, s.size() - 1);
    // we then reverse the word one by one.
    int i = 0, j = 0;
    while(j <= s.size()) {
        if(s[j] != ' ' && s[j] != '\0') {
            j++;
        } else {
            reverseWord(s, i, j - 1);
            j++;
            i = j;
        }
    }
}

int main(void) {
    string words = "  abc   dc";
    removeSpaces(words);
    reverseWords(words);
    cout << words << endl;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值