File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ // n: len(str)
2
+ // Time complexity: O(n)
3
+ // Space complexity: O(1)
4
+ const encode = function ( arr ) {
5
+ let answer = "" ;
6
+
7
+ for ( const word of arr ) {
8
+ answer += `${ word . length } ${ SEPERATOR } ` ;
9
+ }
10
+
11
+ return answer ;
12
+ } ;
13
+
14
+ // n: len(str)
15
+ // Time complexity: O(n)
16
+ // Space complexity: O(n)
17
+ const decode = function ( str ) {
18
+ const SEPERATOR = "|" ;
19
+ const words = [ ] ;
20
+
21
+ let i = 0 ;
22
+ let wordLength = "" ;
23
+
24
+ while ( i < str . length ) {
25
+ if ( str [ i ] === SEPERATOR ) {
26
+ words . push ( str . slice ( i + 1 , i + 1 + Number ( wordLength ) ) ) ;
27
+ i += Number ( wordLength ) + 1 ;
28
+ wordLength = "" ;
29
+ continue ;
30
+ }
31
+
32
+ wordLength += str [ i ] ;
33
+ i += 1 ;
34
+ }
35
+
36
+ return words ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments