-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path151.ReverseWorldString.cpp
More file actions
executable file
·129 lines (112 loc) · 2.69 KB
/
151.ReverseWorldString.cpp
File metadata and controls
executable file
·129 lines (112 loc) · 2.69 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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
@copyright 2004-2015 Apache License, Version 2.0
@filename 151.ReverseWorldString.cpp
@author root
@version
@date 2019/09/27 01:02
@brief
@details 2019/09/27 root create
*/
#include "common_define.h"
class Solution
{
public:
// runtime o(n) memory o(n)
string reverseWords(string s)
{
int len = s.size();
bool isSplit = false;
std::vector<std::string> total_string;
std::string tmp_str;
for (int i = 0; i < len; i++)
{
if (s[i] == ' ')
{
isSplit = false;
if (!tmp_str.empty())
{
total_string.push_back(tmp_str);
tmp_str.clear();
}
continue;
}
else
{
isSplit = true;
tmp_str += s[i];
}
}
if (!tmp_str.empty())
{
total_string.push_back(tmp_str);
tmp_str.clear();
}
std::reverse(total_string.begin(), total_string.end());
string ret_str;
for (int i = 0; i < total_string.size(); i++)
{
if (i == total_string.size() - 1)
{
ret_str += total_string[i];
}
else
{
ret_str += total_string[i] + " ";
}
}
return ret_str;
}
string reverseWords1(string s)
{
auto local_resvere =[](string & s, int begin, int end)->void
{
while (begin < end)
{
int tmp = s[begin];
s[begin] = s[end];
s[end] = tmp;
begin++;
end--;
}
};
int i = 0;
int j = 0;
int len = s.length();
int word = 0;
while (true)
{
// trim left space
while (i < len && s[i] == ' ')
{
i++;
}
if (i == len)
{
break;
}
if (word)
{
s[j++] = ' ';
}
int start = j;
while (i < len && s[i] != ' ')
{
s[j++] = s[i++];
}
local_resvere(s, start, j - 1);
word++;
}
s.resize(j);
std::reverse(s.begin(), s.end());
return s;
}
};
int main()
{
Solution s;
cout << s.reverseWords1(" ") << endl;
cout << s.reverseWords1("hello world hulk") << endl;
cout << s.reverseWords1(" hello world hulk ") << endl;
cout << s.reverseWords1(" hello world hulk ") << endl;
return 0;
}