Skip to content

Commit a92eb7e

Browse files
committed
encode-and-decode-string solution
1 parent dedc040 commit a92eb7e

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
/**
3+
* @param {string[]} strs
4+
* @returns {string}
5+
*/
6+
encode(strs) {
7+
let result = "";
8+
9+
for (const str of strs) {
10+
result += `${str.length}#${str}`;
11+
}
12+
13+
return result;
14+
}
15+
16+
/**
17+
* @param {string} str
18+
* @returns {string[]}
19+
*/
20+
decode(s) {
21+
let result = [];
22+
let i = 0;
23+
// 5#hello5#world
24+
while (i < s.length) {
25+
const pos = s.indexOf("#", i);
26+
const len = parseInt(s.slice(i, pos));// 5
27+
i = pos + 1;
28+
const str = s.slice(i, i + len);
29+
result.push(str);
30+
i += len;
31+
}
32+
return result;
33+
}
34+
}
35+

0 commit comments

Comments
 (0)