forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspace-replacement.cpp
34 lines (30 loc) · 913 Bytes
/
space-replacement.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
int replaceBlank(char string[], int length) {
const array<char, 3> to{'%', '2', '0'};
int space_count = 0;
for (int i = 0; i < length; ++i) {
if (string[i] == ' ') {
++space_count;
}
}
const int new_length = length +
(static_cast<int>(to.size()) - 1) * space_count;
for (int i = length - 1, j = new_length - 1; i >= 0; --i) {
if (string[i] == ' ') {
j -= to.size();
copy(to.cbegin(), to.cend(), string + j + 1);
} else {
string[j--] = string[i];
}
}
return new_length;
}
};