-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_words_in_a_string.cpp
More file actions
61 lines (48 loc) · 1.59 KB
/
reverse_words_in_a_string.cpp
File metadata and controls
61 lines (48 loc) · 1.59 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
151. Reverse Words in a String
Time Complexity: O(n)
Space Complexity: O(n) for the result
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
stringstream ss(s);
string word;
vector<string> words;
while (ss >> word) {
words.push_back(word);
}
reverse(words.begin(), words.end());
string result = "";
for (int i = 0; i < words.size(); i++) {
result += words[i];
if (i < words.size() - 1) {
result += " ";
}
}
return result;
}
};
// Test cases
int main() {
Solution solution;
// Example 1
cout << "Example 1: '" << solution.reverseWords("the sky is blue") << "'" << endl; // Expected: "blue is sky the"
// Example 2
cout << "Example 2: '" << solution.reverseWords(" hello world ") << "'" << endl; // Expected: "world hello"
// Example 3
cout << "Example 3: '" << solution.reverseWords("a good example") << "'" << endl; // Expected: "example good a"
// Edge case: single word
cout << "Example 4: '" << solution.reverseWords("hello") << "'" << endl; // Expected: "hello"
// Edge case: two words
cout << "Example 5: '" << solution.reverseWords("hello world") << "'" << endl; // Expected: "world hello"
// Edge case: lots of spaces
cout << "Example 6: '" << solution.reverseWords(" a b c ") << "'" << endl; // Expected: "c b a"
return 0;
}