-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreversewordofstring.cpp
More file actions
50 lines (42 loc) · 1.02 KB
/
Copy pathreversewordofstring.cpp
File metadata and controls
50 lines (42 loc) · 1.02 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
// class Solution {
// public:
// string reverseWords(string s) {
// string result;
// int i = 0;
// int n = s.length();
// while(i < n){
// while(i < n && s[i] == ' ') i++;
// if(i >= n) break;
// int j = i + 1;
// while(j < n && s[j] != ' ') j++;
// string sub = s.substr(i, j-i);
// if(result.length() == 0) result = sub;
// else result = sub + " " + result;
// i = j+1;
// }
// return result;
// }
// };
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
string reverserword(string s ){
int length = s.size();
string result = "";
int i = 0;
while(i<length ){
while(i<length and s[i]==' ')i++;
if(i>=length)break;
int j = i+1;
while(j<length and s[j]!=' ')j++;
string sub = s.substr(i,j-i);
if(result.size() == 0) result = sub;
else result = sub +" "+result;
i =j+1;
}
return result;
}
int main(){
cout<<reverserword("hello World");
return 0;
}