[LeetCode] Reverse Words in a String

题目

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

给定一个输入字符串,逐个单词地翻转字符串。

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

分析

最直观的的思路是先将字符串中单词反转,再将整个字符串翻转。这样的思路没有问题,但要考虑到多余空格。

思路
  1. 处理字符串前后多余空格。
  2. 遍历字符串剩余字符串,用单词填补空格,并将其翻转。
  3. 处理字符串中多余空白:翻转单词后,添加一个空格,遇到其他空格直接忽略。
  4. 调整字符串大小,翻转整个字符串。

代码

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    void reverseWord(string &s, int start, int end) {
        while (start < end) {
            char temp = s[start];
            s[start++] = s[end];
            s[end--] = temp;
        }
    }

    void reverseWords(string &s) {
        int start = 0, copy = 0;
        int length = s.length();
        int leftSpaces = 0, rightSpaces = 0;

        for (int i = 0; i < length; i++) {
            if (s[i] != ' ') {
                break; 
            } else {
                leftSpaces++;
            }
        }
        if (leftSpaces == length) {
            s = "";
            return ;
        }
        for (int j = length - 1; j > 0; j--) {
            if (s[j] != ' ') {
                break;
            } else {
                rightSpaces++;
            }
        } 

        for (int i = leftSpaces; i < length - rightSpaces;) { 
            start = copy;
            while (i < length - rightSpaces && s[i] != ' ') {
                s[copy++] = s[i++];
            } 
            reverseWord(s, start, copy - 1);
            if (i < length - rightSpaces && copy > 0) {
                s[copy++] = ' ';
            }   
            while (i < length - rightSpaces && s[i] == ' ') {
                i++;
            } 
        }

        s.resize(copy);
        reverseWord(s, 0, copy - 1);
    }
};

int main() {
    Solution solution;
    string s = "  abc   efg   ";
    cout << "Result:" << s << "(start)"<<endl;  
    solution.reverseWords(s);
    cout << "Result:" << s << "(end)"<<endl;  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值