File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ const DELIMITER = "#" ;
2+
3+ /**
4+ *
5+ * @param {string[] } strs
6+ * @returns {string }
7+ */
8+ function encode ( strs ) {
9+ return strs . map ( ( s ) => `${ s . length } ${ DELIMITER } ${ s } ` ) . join ( "" ) ;
10+ }
11+
12+ /**
13+ *
14+ * @param {string } encodedStr
15+ * @returns {string[] }
16+ */
17+ function decode ( encodedStr ) {
18+ const decodedStrings = [ ] ;
19+ let currentIndex = 0 ;
20+
21+ while ( currentIndex < encodedStr . length ) {
22+ let delimiterIndex = currentIndex ;
23+
24+ while ( encodedStr [ delimiterIndex ] !== DELIMITER ) {
25+ delimiterIndex += 1 ;
26+ }
27+
28+ const strLength = parseInt (
29+ encodedStr . substring ( currentIndex , delimiterIndex )
30+ ) ;
31+
32+ decodedStrings . push (
33+ encodedStr . substring ( delimiterIndex + 1 , delimiterIndex + 1 + strLength )
34+ ) ;
35+
36+ currentIndex = delimiterIndex + 1 + strLength ;
37+ }
38+
39+ return decodedStrings ;
40+ }
41+ /**
42+ * Time Complexity: O(n) where n is the length of the encoded string.
43+ * Reason:
44+ * The inner operations (finding # and extracting substrings) are proportional to the size of the encoded segments
45+ * but are ultimately bounded by the total length of the input string.
46+ *
47+ * Space Complexity: O(k) where k is the total length of the decoded strings.
48+ */
49+
50+ /**
51+ * Test cases
52+ */
53+ const strs4 = [ "longestword" , "short" , "mid" , "tiny" ] ;
54+ const encoded4 = encode ( strs4 ) ;
55+ console . log ( encoded4 ) ; // Output: "11#longestword5#short3#mid4#tiny"
56+
57+ const decoded4 = decode ( encoded4 ) ;
58+ console . log ( decoded4 ) ; // Output: ["longestword", "short", "mid", "tiny"]
You can’t perform that action at this time.
0 commit comments