-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencodeDecode.js
More file actions
63 lines (51 loc) · 1.38 KB
/
encodeDecode.js
File metadata and controls
63 lines (51 loc) · 1.38 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
56
57
58
59
60
61
62
63
// String Encode and Decode
// Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings.
// Please implement encode and decode
// Example 1:
// Input: ["neet","code","love","you"]
// Output:["neet","code","love","you"]
// Example 2:
// Input: ["we","say",":","yes"]
// Output: ["we","say",":","yes"]
// Constraints:
// 0 <= strs.length < 100
// 0 <= strs[i].length < 200
// strs[i] contains only UTF-8 characters.
class Solution {
/**
* @param {string[]} strs
* @returns {string}
*/
encode(strs) {
let result = '';
for (let s of strs) {
result += `${s.length}#${s}`;
}
return result;
}
/**
* @param {string} str
* @returns {string[]}
*/
decode(str) {
let result = [];
let i = 0;
while (i < str.length) {
let j = i;
while (str[j] !== '#' && j < str.length) {
j++;
}
let length = parseInt(str.substring(i, j), 10);
i = j + 1;
j = i + length;
result.push(str.substring(i,j));
i = j;
}
return result;
}
}
const solution = new Solution();
// Example 1
let input1 = ["neet","code","love","you"];
console.log(solution.encode(input1));
console.log(solution.decode(input1));