Cover image for Interview Classic 150 Questions P151 Reverse Words in a String

Interview Classic 150 Questions P151 Reverse Words in a String


Timeline

Timeline

2025-11-09

init

stringstream

Problem:

stringstream

Use stringstream to get each word:

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
#include <sstream>
#include <stack>
#include <string>

using std::stringstream;
using std::string;
using std::stack;

class Solution {
public:
string reverseWords(string s)
{
stack<string> st;
stringstream ss(s);
string tmp, res;

while (ss >> tmp) {
st.push(tmp);
}

while (!st.empty()) {
tmp = st.top();
st.pop();
res += tmp;
res += " ";
}
res.pop_back(); // Remove the last space
return res;
}
};

Two pointers

You can also use two pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string reverseWords(string s) {
// Use two pointers
int m = s.size() - 1;
string res;
// Remove trailing spaces
while (s[m] == ' ' && m > 0) m--;
int n = m; // n is another pointer
while (m >= 0) {
while (m >= 0 && s[m] != ' ') m--;
res += s.substr(m + 1, n - m) + " "; // Get the word and add a space
while (m >= 0 && s[m] == ' ') m--;
n = m;
}
return res.substr(0, res.size() - 1); // ignore the trailing space
}
};