151. Reverse Words in a String

195 篇文章 0 订阅
问题描述

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.

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.

题目链接:


思路分析

将一个字符串中的单词反序输出。字符串中词与词之间可能有多个空格。

使用两个指针,思路分为三步:第一步是去除多余的空格,利用快指针i遍历,找到下一个单词,然后慢指针j用来构建新的字符串;如果i跑出了s的范围,循环结束。第二步,将每个单词逆序,记录新字符串单词的开始位置,然后将其reverse;在下一个循环,j开始新单词之前插入空格‘ ’。第三步,将整个字符串翻转。

代码
class Solution {
public:
    void reverseWords(string &s) {
        int length = s.length();
        int i = 0, j = 0;
        while (true){
            while (i < length && s[i] == ' ') i++;
            if (i >= length) break;
            if (j > 0) s[j++] = ' ';
            int start = j;
            while (i < length && s[i] != ' '){
                s[j++] = s[i++];
            }
            reverse(s.begin() + start, s.begin() + j);
        }
        s.resize(j);
        reverse(s.begin(), s.end());
    }
};

时间复杂度: O(n)
空间复杂度: O(1)


反思

心情也是挺日狗的,medium的题就能把我难住,自己对于问题的抽象理解能力还不是很到位,没找到问题的关键——使用两个指针这样的方法。

对于问题,首先是考虑需要进行的操作,然后考虑的是这样的操作我可以用什么样的方法来实现,使用什么样的编程方式和技巧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值