题目:

给你一个字符串 s ,请你反转字符串中 单词 的顺序。

单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。

返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。

注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。

示例 1:

1
2
输入:s = "the sky is blue"
输出:"blue is sky the"

示例 2:

1
2
3
输入:s = "  hello world  "
输出:"world hello"
解释:反转后的字符串中不能存在前导空格和尾随空格。

示例 3:

1
2
3
输入:s = "a good   example"
输出:"example good a"
解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。

提示:

1 <= s.length <= 104
s 包含英文大小写字母、数字和空格 ' '
s 中 至少存在一个 单词

解题思路:

1. API

这个只有Python和java能使用,c++不支持

Python中的 split reversed join

2. 双端队列

LC151

我们定义了两个指针分别是 leftright

我们对字符串 s 进行删除前导空格以及尾随空格的操作,并不需要真的去删除,而是移动我们的 leftright

创建一个双端队列 qword 来字符串

因为双端队列的特性,我们可以将字符串从后面移动到前面,我们只要遍历字符串 s 然后将字符一个一个添加进队列即可。

至于单词中如果有多余的空格,我们可以在遍历 s 的同时处理。

代码:

Python

API:

1
2
def reverseWords(s: str) -> str:
return " ".join(reversed(s.split()))

双端队列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
def reverseWords(self, s: str) -> str:
from collections import deque
left, right = 0, len(s) - 1

# 去除前导空格
while left <= right and s[left] == ' ':
left += 1

# 去除尾随空格
while left <= right and s[right] == ' ':
right -= 1
# q为双端队列,word用来储存单词
q, word = deque(), []
while left <= right:
# 这样可以避免出现单词之间1个以上的空格
if s[left] == ' ' and word:
q.appendleft(''.join(word))
word = []
elif s[left] != ' ':
word.append(s[left])
left += 1
# 将剩余的单词添加进队列
q.appendleft(''.join(word))
return ' '.join(q)

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
string reverseWords(string s) {

int left = 0, right = s.size() - 1;
// 删除前导空格
while (left <= right && s[left] == ' ') ++left;
// 删除尾随空格
while (left <= right && s[right] == ' ') --right;

deque<string> q;
string word;
while (left <= right) {
char c = s[left];
// 避免单词之间出现1个以上的空格
if (word.size() && c == ' ') {
q.push_front(move(word));
word = "";
}
else if (c != ' ') word += c;
++left;
}
q.push_front(move(word));

// c++没有join,所以要自己添加。
string ans;
while (!q.empty()) {
ans += q.front();
q.pop_front();
if (!q.empty()) ans += ' ';
}
return ans;
}
};