-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_STO_0005_replaceSpace.cc
More file actions
63 lines (57 loc) · 998 Bytes
/
Copy pathProblem_STO_0005_replaceSpace.cc
File metadata and controls
63 lines (57 loc) · 998 Bytes
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
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
string replaceSpace1(string s)
{
int space = 0;
int len = s.length();
for (auto &c : s)
{
if (c == ' ')
{
space++;
}
}
s.resize(len + 2 * space);
for (int i = len - 1, j = s.length() - 1; i >= 0; i--, j--)
{
if (s[i] != ' ')
{
s[j] = s[i];
}
else
{
s[j - 2] = '%';
s[j - 1] = '2';
s[j] = '0';
j -= 2;
}
}
return s;
}
string replaceSpace2(string s)
{
int pos = 0;
while ((pos = s.find(" ")) != string::npos)
{
s.replace(pos, 1, "%20");
}
return s;
}
};
void testReplaceSpace()
{
Solution s;
EXPECT_TRUE("We%20are%20happy." == s.replaceSpace1("We are happy."));
EXPECT_TRUE("We%20are%20happy." == s.replaceSpace2("We are happy."));
EXPECT_SUMMARY;
}
int main()
{
testReplaceSpace();
return 0;
}