-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path151. Reverse Words in a String
More file actions
44 lines (34 loc) · 1.09 KB
/
151. Reverse Words in a String
File metadata and controls
44 lines (34 loc) · 1.09 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
class Solution {
public:
string reverseWords(string s) {
vector<string> reverse;
int sLength = s.length();
bool wordStarted = false;
string currentWord = "";
for(int i = 0; i < sLength; i++) {
if (s[i] != 32 && wordStarted) {
currentWord += s[i];
}
if (s[i] == 32 && wordStarted) {
wordStarted = false;
reverse.push_back(currentWord);
currentWord = "";
}
if(s[i] != 32 && !wordStarted) {
wordStarted = true;
currentWord += s[i];
}
if (i == sLength - 1 && wordStarted) {
reverse.push_back(currentWord);
}
}
string returnString = "";
int reverseSize = reverse.size();
for(int i = reverseSize - 1; i >= 0; i--) {
returnString += reverse.at(i);
returnString += " ";
}
returnString.pop_back();
return returnString;
}
};