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
.
解题思路
要反转字符串中单词的顺序,可以采用以下步骤:
-
创建一个
stringstream
对象ss
,用于将输入的字符串s
按照空格自动分割成单词。 -
初始化两个字符串
word
和result
,分别用于存储当前正在处理的单词和最终的结果。 -
使用
while
循环从ss
中逐个提取单词,将其存储在word
中。 -
在循环中,检查如果
result
不为空,说明已经处理了至少一个单词,那么将当前单词word
与result
连接,并在中间加上一个空格,以构建新的result
。否则,直接将word
赋值给result
。 -
重复步骤3和步骤4,直到处理完所有的单词。
-
返回
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;
}
};