File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ private DELIMITER = "*" ;
3+
4+ /**
5+ * @param strs: a list of strings
6+ * @returns : encodes a list of strings to a single string.
7+ */
8+ public encode ( strs : string [ ] ) : string {
9+ let encoded = "" ;
10+
11+ for ( const str of strs ) {
12+ encoded += `${ str . length } ${ this . DELIMITER } ${ str } ` ;
13+ }
14+
15+ return encoded ;
16+ }
17+
18+ /**
19+ * @param str: A string
20+ * @returns : decodes a single string to a list of strings
21+ */
22+ public decode ( str : string ) : string [ ] {
23+ const decoded : string [ ] = [ ] ;
24+
25+ let stack : string [ ] = [ ] ;
26+ let pointer = 0 ;
27+
28+ while ( pointer < str . length ) {
29+ const char = str [ pointer ] ;
30+
31+ if ( char === this . DELIMITER ) {
32+ let strLength : number = Number ( stack . join ( "" ) ) ;
33+ stack = [ ] ;
34+
35+ const word = str . substring ( pointer + 1 , pointer + 1 + strLength ) ;
36+ pointer = pointer + 1 + strLength ;
37+
38+ decoded . push ( word ) ;
39+ } else {
40+ stack . push ( char ) ;
41+ pointer ++ ;
42+ }
43+ }
44+
45+ return decoded ;
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments