-
Notifications
You must be signed in to change notification settings - Fork 1
/
Reverse words in a given string.cpp
78 lines (61 loc) · 1.74 KB
/
Reverse words in a given string.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
72
73
74
75
76
77
78
/*Given a String S, reverse the string without reversing its individual words. Words are separated by dots.
Example 1:
Input:
S = i.like.this.program.very.much
Output: much.very.program.this.like.i
Explanation: After reversing the whole
string(not individual words), the input
string becomes
much.very.program.this.like.i
Example 2:
Input:
S = pqr.mno
Output: mno.pqr
Explanation: After reversing the whole
string , the input string becomes
mno.pqr
Your Task:
You dont need to read input or print anything. Complete the function reverseWords() which takes string S as input parameter and returns a string containing the words in reversed order. Each word in the returning string should also be separated by '.'
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)
Constraints:
1 <= |S| <= 2000 */
#include <bits/stdc++.h>
using namespace std;
// Function to reverse words*/
void reverseWords(string s)
{
// temporary vector to store all words
vector<string> tmp;
string str = "";
for (int i = 0; i < s.length(); i++)
{
// Check if we encounter space
// push word(str) to vector
// and make str NULL
if (s[i] == ' ')
{
tmp.push_back(str);
str = "";
}
// Else add character to
// str to form current word
else
str += s[i];
}
// Last word remaining,add it to vector
tmp.push_back(str);
// Now print from last to first in vector
int i;
for (i = tmp.size() - 1; i > 0; i--)
cout << tmp[i] << " ";
// Last word remaining,print it
cout << tmp[0] << endl;
}
// Driver Code
int main()
{
string s = "i like this program very much";
reverseWords(s);
return 0;
}