Skip to content

Commit 8f6c82f

Browse files
committed
feat: 659.encode-and-decode-strings
1 parent a302c0f commit 8f6c82f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// n: len(str)
2+
// Time complexity: O(n)
3+
// Space complexity: O(1)
4+
const encode = function (arr) {
5+
let answer = "";
6+
7+
for (const word of arr) {
8+
answer += `${word.length}${SEPERATOR}`;
9+
}
10+
11+
return answer;
12+
};
13+
14+
// n: len(str)
15+
// Time complexity: O(n)
16+
// Space complexity: O(n)
17+
const decode = function (str) {
18+
const SEPERATOR = "|";
19+
const words = [];
20+
21+
let i = 0;
22+
let wordLength = "";
23+
24+
while (i < str.length) {
25+
if (str[i] === SEPERATOR) {
26+
words.push(str.slice(i + 1, i + 1 + Number(wordLength)));
27+
i += Number(wordLength) + 1;
28+
wordLength = "";
29+
continue;
30+
}
31+
32+
wordLength += str[i];
33+
i += 1;
34+
}
35+
36+
return words;
37+
};

0 commit comments

Comments
 (0)