-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path151_reverse_words.cpp
71 lines (60 loc) · 1.31 KB
/
151_reverse_words.cpp
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
62
63
64
65
66
67
68
69
70
71
// LC - 151. Reverse Words in a String
// Return a string of the words in reverse order concatenated by a single space.
#include <bits/stdc++.h>
using namespace std;
// TC AND SC = O(N)
string reverseWords(string s) {
reverse(s.begin(), s.end());
string ans;
int i = 0;
while(i< s.length()) {
while(i<s.length() && s[i] == ' ') {
i++;
}
string temp;
while(i<s.length() && s[i] != ' ') {
temp = s[i] + temp;
i++;
}
if (!temp.empty()) {
if (!ans.empty()) {
ans = ans + ' ' + temp;
} else {
ans = temp;
}
}
}
return ans;
}
/*
string reverseWords(string s) {
string temp = "";
stack<string>st;
for(int i=0; i<s.size();i++){
char ch = s[i];
if(ch == ' '){
if(temp != "")
st.push(temp);
temp = "";
}
else
temp+=ch;
}
if(temp!=""){
st.push(temp);
}
string ans = "";
while(!st.empty()){
ans+=(st.top()+" ");
st.pop();
}
ans.pop_back();
return ans;
}
*/
int main() {
string s;
getline(cin, s); // read the entire line of input even the whitespaces
cout << reverseWords(s);
return 0;
}