File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://neetcode.io/problems/string-encode-and-decode
2+
3+ class Solution {
4+ /**
5+ * @param {string[] } strs
6+ * @returns {string }
7+ */
8+ encode ( strs ) {
9+ let encodedStrings : string [ ] = [ ] ;
10+
11+ for ( const word of strs ) {
12+ const length = word . length ;
13+ encodedStrings . push ( `${ length } #${ word } ` ) ;
14+ }
15+
16+ return encodedStrings . join ( "" ) ;
17+ }
18+
19+ /**
20+ * @param {string } str
21+ * @returns {string[] }
22+ */
23+ decode ( str ) {
24+ const decodedStrings : string [ ] = [ ] ;
25+ let position = 0 ;
26+
27+ while ( position < str . length ) {
28+ const hashIndex = str . indexOf ( "#" , position ) ;
29+ const length = Number ( str . slice ( position , hashIndex ) ) ;
30+
31+ const start = hashIndex + 1 ;
32+ const end = start + length ;
33+ const word = str . slice ( start , end ) ;
34+ decodedStrings . push ( word ) ;
35+
36+ position = end ;
37+ }
38+
39+ return decodedStrings ;
40+ }
41+ } ;
You can’t perform that action at this time.
0 commit comments