LintCode 927: Reverse Words in a String

本文深入探讨了如何使用C++实现字符串的单词反转,重点讲解了string.find()方法的应用,通过实例展示了如何在不分配额外空间的情况下,按单词逆序排列字符串。

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

题目如下:
927. Reverse Words in a String II
Given an input character array, reverse the array word by word. A word is defined as a sequence of non-space characters.

The input character array does not contain leading or trailing spaces and the words are always separated by a single space.

Example
Given s = “the sky is blue”,
after reversing : “blue is sky the”

Challenge
Could you do it in-place without allocating extra space?

这题主要考string.find()的用法。
注意string.find(’ ', endPos+1)里面的endPos+1可以表示从什么地方开始找。

class Solution {
public:
    /**
     * @param str: a string
     * @return: return a string
     */
    string reverseWords(string &str) {
        string result;
        int startPos = -1, endPos = 0;
        size_t len = str.size();
        
        while (endPos < len) {
  
            endPos = str.find(' ', endPos + 1);
            if (startPos >= 0)
                result = str.substr(startPos + 1, endPos - startPos - 1) + ' ' + result;
            else 
                result = str.substr(startPos + 1, endPos);

            startPos = endPos;
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值