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

Top 150 Interview Questions P151 Reverse Words in a String


Timeline

Timeline

2025-11-09

init

stringstream

Problem:

stringstream

Use stringstream to get each word:

123456789101112131415161718192021222324252627282930
#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

123456789101112131415161718
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 last space    }};
Loading comments…