-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path557.cpp
More file actions
48 lines (45 loc) · 1.14 KB
/
557.cpp
File metadata and controls
48 lines (45 loc) · 1.14 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
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
string reverseWords(string s)
{
char cSubString;
string outputStr;
int prev = 0;
int detect = 0;
for(int i=0; i < s.length(); i++)
{
cSubString = (s.substr(i,1))[0];
// if ' ' detected, then reverse the word.
if(cSubString == ' ')
{
detect = i;
for(int j = detect-1; j >= prev; j--)
{
cSubString = (s.substr(j, 1))[0];
outputStr += cSubString;
}
prev = detect+1;
outputStr += ' ';
}
if(i == s.length()-1)
{
detect = i+1;
for(int j = detect-1; j >= prev; j--)
{
cSubString = (s.substr(j, 1))[0];
outputStr += cSubString;
}
}
}
return outputStr;
}
};
int main()
{
Solution solution;
std::cout << solution.reverseWords("Hello world") << std::endl;
return 0;
}