File tree 1 file changed +47
-0
lines changed
encode-and-decode-strings
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Encodes a list of strings to a single string.
3
+ *
4
+ * @param {string[] } strs
5
+ * @return {string }
6
+ */
7
+
8
+ const DELIMITER = "#" ;
9
+
10
+ var encode = function ( strs ) {
11
+ let temp = "" ;
12
+ for ( const str of strs ) { // encode using the delimiter by attaching the length of the array as well
13
+ temp += `${ str . length } ${ DELIMITER } ` + str ;
14
+ }
15
+ return temp ;
16
+ } ;
17
+
18
+ /**
19
+ * Decodes a single string to a list of strings.
20
+ *
21
+ * @param {string } s
22
+ * @return {string[] }
23
+ */
24
+ var decode = function ( s ) { // decode using the length of array that is attached with the delimiter
25
+ let result = [ ] ;
26
+ let i = 0 ;
27
+ while ( i < s . length ) {
28
+ let j = i ;
29
+ while ( s [ j ] !== DELIMITER ) j ++ ;
30
+ const len = Number ( s . slice ( i , j ) ) ;
31
+ const word = s . slice ( j + 1 , j + len + 1 ) ;
32
+ result . push ( word ) ;
33
+ i = j + len + 1 ;
34
+ }
35
+ return result ;
36
+ } ;
37
+
38
+ /**
39
+ * Your functions will be called as such:
40
+ * decode(encode(strs));
41
+ */
42
+
43
+ // test cases
44
+ console . log ( [ "Hello" , "World" ] ) ;
45
+
46
+ // time - O(n) - iterate through the list of strings once
47
+ // space - O(n) - stores the strings
You can’t perform that action at this time.
0 commit comments