-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathencodeDecodeStrings.js
More file actions
54 lines (51 loc) · 1.22 KB
/
encodeDecodeStrings.js
File metadata and controls
54 lines (51 loc) · 1.22 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
/**
* TC: O(n) SC: O(n)
* Encodes a list of strings to a single string.
* Uses length-prefix encoding with '#' as a delimiter.
* @param {string[]} strs
* @returns {string}
*/
function encodeStrings(strs) {
let encodedStr = "";
for (let str of strs) {
encodedStr += str.length + "#" + str;
}
return encodedStr;
}
/**
* Decodes a single string to a list of strings.
* @param {string} str
* @returns {string[]}
*/
function decodeString(str) {
let decodedStrArr = [];
let i = 0;
while (i < str.length) {
let j = i;
while (str[j] !== "#" && j < str.length) j++;
let wordLength = Number.parseInt(str.substring(i, j));
let start = j + 1;
let subStr = str.substring(start, start + wordLength);
decodedStrArr.push(subStr);
i = start + wordLength;
}
return decodedStrArr;
}
// Test cases
const testCases = [
["learn", "datastructure", "algorithms", "easily"],
["one", "two", "three"],
["", "a", ""],
["#", "##", "abc#def"],
[],
["", ""],
];
for (const arr of testCases) {
const encoded = encodeStrings(arr);
const decoded = decodeString(encoded);
console.log(
`Input: ${JSON.stringify(
arr
)} | Encoded: "${encoded}" | Decoded: ${JSON.stringify(decoded)}`
);
}