-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_words.cpp
71 lines (67 loc) · 1.69 KB
/
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
/*
* =====================================================================================
*
* Filename: reverse_words.cpp
*
* Description: 151. Reverse Words in a String.
*
* Version: 1.0
* Created: 04/10/19 05:04:08
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
class Solution
{
public:
std::string reverseWords(const std::string& s)
{
std::string r(s.size() + 1, '\0');
size_t start = r.size();
size_t count = 0;
size_t idx = 0;
while (idx < s.size())
{
size_t pos = s.find(' ', idx);
if (pos == std::string::npos)
{
count = s.size() - idx;
start -= count;
r.replace(start, count, s, idx, count);
r[--start] = ' ';
break;
}
else if (pos == idx)
{
idx = pos + 1;
}
else
{
count = pos - idx;
start -= count;
r.replace(start, count, s, idx, count);
r[--start] = ' ';
idx = pos + 1;
}
}
if (r[start] == ' ')
{
start++;
}
return r.substr(start);
}
};
int main(int argc, char* argv[])
{
std::string s = "the sky is blue";
auto r = Solution().reverseWords(s);
printf("Input: `%s`\nOutput:`%s`\n", s.c_str(), r.c_str());
return 0;
}