-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse the String
56 lines (31 loc) · 1.02 KB
/
Reverse the String
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
Given a string A.
Return the string A after reversing the string word by word.
NOTE:
A sequence of non-space characters constitutes a word.
Your reversed string should not contain leading or trailing spaces, even if it is present in the input string.
If there are multiple spaces between words, reduce them to a single space in the reversed string.
Input Format
The only argument given is string A.
Output Format
Return the string A after reversing the string word by word.
For Example
Input 1:
A = "the sky is blue"
Output 1:
"blue is sky the"
Input 2:
A = "this is ib"
Output 2:
"ib is this"
//Solutions
string Solution::solve(string A) {
reverse(begin(A),end(A));// reverse the whole string
int b=0, e=0;
for(e=0;e<A.length();e++)
if(A[e]==' ') {
reverse(A.begin()+b, A.begin()+e);//reverse the each word
b=e+1;
}
reverse(A.begin()+b,A.end()); //for the last word
return A;
}