Skip to content

Commit c3a1a7e

Browse files
authored
Create main.cpp
1 parent 306a33c commit c3a1a7e

File tree

1 file changed

+37
-0
lines changed
  • 25 - Greedy Algorithm Problems/05 - Reverse Words

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

0 commit comments

Comments
 (0)