-
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathurlify.js
More file actions
55 lines (43 loc) · 1.35 KB
/
urlify.js
File metadata and controls
55 lines (43 loc) · 1.35 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
// URLlify: Write a method to replace all spaces in a string with '%20'.
// You may assume that the string has sufficient space at the end to hold the additional characters,
// and that you are given the "true" length of the string
// Runtime Complexity: O(N), where N = the true length of the string
// Space Complexity: O(N), where N = the true length of the string in the new array
export function urlify(string, length, placeholder = '%20') {
let output = [];
let lastChar = '';
let space = ' ';
for (let index = 0; index < length; index++) {
let char = string[index];
if (char !== space) {
output.push(char);
}
if (char === space && lastChar !== space) {
output.push(placeholder);
}
lastChar = char;
}
return output.join('');
}
// Runtime Complexity: O(N), where N = the true length of the string
// Space Complexity: O(N), where N = the true length of the string in the new array
export function urlifyForward(string, length, placeholder = '%20') {
let output = [];
let index = 0;
let space = ' ';
const moveForward = () => {
while (string[index] === space) {
index++;
}
};
while (index < length) {
if (string[index] === space) {
output.push(placeholder);
moveForward();
} else {
output.push(string[index]);
index++;
}
}
return output.join('');
}