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

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;
    }
};

你可能感兴趣的:(LeetCode,面试经典150题,c#,服务器,开发语言)