-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencodeDecode.js
More file actions
39 lines (29 loc) · 1.07 KB
/
encodeDecode.js
File metadata and controls
39 lines (29 loc) · 1.07 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
/**
* Encode and Decode Strings
* Design an algorithm to encode a list of strings to a string.
* The encoded string is then sent over the network and is decoded back to the original list of strings.
*/
function encodeDecode(){
function encode(strs) {
let encoded = ""
for(let str of strs){
encoded += str.length + "#" + str //add the number of 1st part of string and delimiter '#' to the beginning of the array
}
return encoded
}
function decode(str) {
let result = []
let i = 0
while(i < str.length){ //iterate i till the end of the string
let j = i
while(str[j] !== "#"){ //iterate j until you reach #
j++
}
let length = parseInt(str.substring(i,j)) //Get the length of the encoded string
let word = str.substring(j+1, j+1+length) // include the string from beginning till end[4#Neet]
result.push(word)
i = j + 1 + length // go to the next word in the array
}
return result
}
}