Skip to content

Commit 685adc5

Browse files
authored
feat: solved URLify with O(n) time complexity (careercup#56)
1 parent 4b10530 commit 685adc5

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

chapter01/1.3 - URLify/urlify-3.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function urlify(str, len) {
2+
let s = "";
3+
let totalSpaces = str.length - len;
4+
let frontSpaces = 0;
5+
let flag = false;
6+
for (let i = 0; i < str.length; i++) {
7+
if (flag === false) {
8+
if (str[i] === " ") frontSpaces++;
9+
else flag = true;
10+
}
11+
if (flag === true && i < str.length - (totalSpaces - frontSpaces)) {
12+
if (str[i] === " ") s += "%20";
13+
else s += str[i];
14+
}
15+
}
16+
17+
return s;
18+
}
19+
20+
console.log(urlify("Mr John Smith ", 13));

0 commit comments

Comments
 (0)