-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path151.cpp
More file actions
43 lines (36 loc) · 1.28 KB
/
Copy path151.cpp
File metadata and controls
43 lines (36 loc) · 1.28 KB
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
35
36
37
38
39
40
41
42
43
/**
* 151. 颠倒字符串中的单词
* 给你一个字符串 s ,颠倒字符串中 单词 的顺序。
* 单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
* 返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
* 注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。
* 返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
* https://leetcode.cn/problems/reverse-words-in-a-string/
*/
class Solution {
public:
string reverseWords(string s) {
if (s.empty()) return s;
int n = s.size();
stack<string> st;
int i = 0;
int start = 0;
while (i < n) {
// 去掉空格
while (i < n && s[i] == ' ') i++;
if (i >= n) break;
start = i; // 单词起始位置
while (i < n && s[i] != ' ') i++;
// 记录单词并入栈
string t = s.substr(start, i - start);
st.push(t);
}
string t = st.top();
st.pop();
while (!st.empty()) {
t += " " + st.top();
st.pop();
}
return t;
}
};