面试经典150题 P151 反转字符串中的单词
时间轴
2025-11-09
init
题目:
stringstream
用stringstream获得每个单词: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
using std::stringstream;
using std::string;
using std::stack;
class Solution {
public:
string reverseWords(string s)
{
stack<string> st;
stringstream ss(s);
string tmp;
string res;
while (ss >> tmp) {
st.push(tmp);
}
while (!st.empty()) {
tmp = st.top();
st.pop();
res += tmp;
res += " ";
}
res.pop_back(); // 去掉最后一个空格
return res;
}
};
双指针
也可以用双指针1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Solution {
public:
string reverseWords(string s) {
// 使用双指针
int m = s.size() - 1;
string res;
// 除去尾部空格
while (s[m] == ' ' && m > 0) m--;
int n = m; // n是另一个指针
while (m >= 0) {
while (m >= 0 && s[m] != ' ') m--;
res += s.substr(m + 1, n - m) + " "; // 获取单词并加上空格
while (m >= 0 && s[m] == ' ') m--;
n = m;
}
return res.substr(0, res.size() - 1); // 忽略最后一位的空格
}
};



