【LeetCode 面试经典150题】151. Reverse Words in a String 反转字符串中的单词

文章讲述了如何使用C++的stringstream反转输入字符串中的单词顺序,处理空格问题,提供示例和解题思路。
摘要由CSDN通过智能技术生成

151. Reverse Words in a String

题目大意

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

中文释义

给定一个输入字符串 s,反转单词的顺序

一个单词被定义为一系列非空格字符。字符串 s 中的单词将至少由一个空格分隔。

返回一个字符串,其中包含反转顺序的单词,由一个单个空格连接起来。

请注意,字符串 s 可能包含前导或尾随空格,或者两个单词之间可能有多个空格。返回的字符串应仅在单词之间保留单个空格,不包括任何额外的空格。

Example

Example 1:

Input: s = “the sky is blue”
Output: “blue is sky the”

Example 2:

Input: s = " hello world "
Output: “world hello”
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = “a good example”
Output: “example good a”
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ’ '.
  • There is at least one word in s.

解题思路

要反转字符串中单词的顺序,可以采用以下步骤:

  1. 创建一个 stringstream 对象 ss,用于将输入的字符串 s 按照空格自动分割成单词。

  2. 初始化两个字符串 wordresult,分别用于存储当前正在处理的单词和最终的结果。

  3. 使用 while 循环从 ss 中逐个提取单词,将其存储在 word 中。

  4. 在循环中,检查如果 result 不为空,说明已经处理了至少一个单词,那么将当前单词 wordresult 连接,并在中间加上一个空格,以构建新的 result。否则,直接将 word 赋值给 result

  5. 重复步骤3和步骤4,直到处理完所有的单词。

  6. 返回 result 作为反转顺序的单词字符串。

这个算法通过 stringstream 自动分割单词,然后在结果字符串中逐个连接它们,实现了反转单词顺序并去除多余空格。

class Solution {
public:
    string reverseWords(string s) {
        stringstream ss(s);
        string word, result;
        while (ss >> word) {
            if (!result.empty()) {
                result = word + " " + result;
            } else {
                result = word;
            }
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值