File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
25 - Greedy Algorithm Problems/05 - Reverse Words Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to reverse words in a given string
4+ string reverseWords (string &s) {
5+ // Create a vector to store individual words from the string
6+ vector<string> words;
7+
8+ // Temporary string to hold each word while reading from the string
9+ string word;
10+
11+ // Create an input string stream to split the string 's' into words
12+ istringstream iss (s);
13+
14+ // While there are words in the string stream, extract them and push to the 'words' vector
15+ while (iss >> word)
16+ words.push_back (word); // Extract each word and add it to the vector
17+
18+ // Reverse the vector of words
19+ reverse (words.begin (), words.end ());
20+
21+ // Initialize an empty string to store the result
22+ string ans = " " ;
23+
24+ // Loop through the reversed vector of words
25+ for (int i = 0 ; i < words.size (); i++){
26+ // Add the current word to the result string
27+ ans += words[i];
28+
29+ // If this is not the last word, add a space between words
30+ if (i != words.size () - 1 )
31+ ans += " " ;
32+ }
33+
34+ // Return the final reversed string
35+ return ans;
36+ }
37+ };
You can’t perform that action at this time.
0 commit comments