[Leetcode] 151. Reverse Words in a String 解题报告

这篇解题报告介绍了如何解决LeetCode上的151题——翻转字符串中的单词。题目要求在O(1)空间复杂度内完成,且要考虑字符串中的多余空格。解题思路包括检测单词并翻转,以及最后对整个字符串的翻转,确保不包含多余前导或尾随空格。

摘要生成于 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".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

思路

刷题刷久了,就忘了面试中关键的一个考察点,就是对一个题目有疑惑的时候,一定要记得和面试官讨论,进行clarification。上面写到的三点clarification都是非常重要的,直接关系到代码该怎么写。

其实算法的思路也算是比较明确的:1)每当检测出来一个单词时,对其进行翻转;2)当所有的单词被检测出来时,对整个字符串再进行一次翻转。由于原字符串中有可能存在多余的空格,所以我们在扫描过程中,需要在字符串内部进行复制,以将多余的空格给覆盖掉。具体见下面的代码片段。该思路的时间复杂度是O(n),空间复杂度是O(1)。

代码

class Solution {
public:
    void reverseWords(string &s) {
        int len = s.size();
        int left = 0, right = 0, i = 0, flag = false;
        while(i < len) {
            while(s[i] == ' ')  // trim the leading space
                i++;
            if(i == len)        // already at the end
                break;
            if(flag)
                s[right++] = ' ';
            left = right;
            while(i < len && s[i] != ' ')
                s[right++] = s[i++];
            reverse(s, left, right-1);
            flag = true;    // flag is used to judge whether append " "
        }
        s.resize(right);
        reverse(s, 0, right - 1);
    }
private:
    void reverse(string&s, int left, int right) {
        while(left < right) {
            char ch = s[right];
            s[right--] = s[left];
            s[left++] = ch;
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值