-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathch1-q3.js
40 lines (36 loc) · 899 Bytes
/
ch1-q3.js
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
'use strict';
/**
* Count the number of spaces in the string to calculate the new length of the
* string and move characters back where required replacing spaces with %20.
*
* N = |url|
* Time: O(N)
* Additional space: O(1)
*
* @param {string[]} url URL string as a character arra which will be updated in place
* @return {string[]} Updated URL character array
*/
export function encodeSpaces(url) {
if (!url || url.length === 0) {
return url;
}
let spaceCount = 0;
for (let ch of url) {
if (ch === ' ') {
++spaceCount;
}
}
// add an extra 2 characters for each space
let newLength = url.length - 1 + 2 * spaceCount;
for (let i = url.length - 1, j = newLength; i >= 0 && j > i; --i, --j) {
if (url[i] === ' ') {
url[j] = '0';
url[--j] = '2';
url[--j] = '%';
}
else {
url[j] = url[i];
}
}
return url;
}