File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 394. Decode String
3
+ * https://leetcode.com/problems/decode-string/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an encoded string, return its decoded string.
7
+ *
8
+ * The encoding rule is: k[encoded_string], where the encoded_string inside the square
9
+ * brackets is being repeated exactly k times. Note that k is guaranteed to be a
10
+ * positive integer.
11
+ *
12
+ * You may assume that the input string is always valid; there are no extra white spaces,
13
+ * square brackets are well-formed, etc. Furthermore, you may assume that the original
14
+ * data does not contain any digits and that digits are only for those repeat numbers, k.
15
+ * For example, there will not be input like 3a or 2[4].
16
+ *
17
+ * The test cases are generated so that the length of the output will never exceed 105.
18
+ */
19
+
20
+ /**
21
+ * @param {string } s
22
+ * @return {string }
23
+ */
24
+ var decodeString = function ( s ) {
25
+ const stack = [ ] ;
26
+ let result = '' ;
27
+ let decoder = 0 ;
28
+
29
+ for ( const c of s ) {
30
+ if ( ! isNaN ( c ) && Number ( c ) >= 0 && Number ( c ) <= 9 ) {
31
+ decoder = Number ( c ) + decoder * 10 ;
32
+ } else if ( c === '[' ) {
33
+ stack . push ( [ result , decoder ] ) ;
34
+ result = '' ;
35
+ decoder = 0 ;
36
+ } else if ( c === ']' ) {
37
+ const [ previous , count ] = stack . pop ( ) ;
38
+ result = previous + result . repeat ( count ) ;
39
+ } else {
40
+ result += c ;
41
+ }
42
+ }
43
+
44
+ return result ;
45
+ } ;
Original file line number Diff line number Diff line change 181
181
383|[ Ransom Note] ( ./0383-ransom-note.js ) |Easy|
182
182
387|[ First Unique Character in a String] ( ./0387-first-unique-character-in-a-string.js ) |Easy|
183
183
392|[ Is Subsequence] ( ./0392-is-subsequence.js ) |Easy|
184
+ 394|[ Decode String] ( ./0394-decode-string.js ) |Medium|
184
185
405|[ Convert a Number to Hexadecimal] ( ./0405-convert-a-number-to-hexadecimal.js ) |Easy|
185
186
412|[ Fizz Buzz] ( ./0412-fizz-buzz.js ) |Easy|
186
187
414|[ Third Maximum Number] ( ./0414-third-maximum-number.js ) |Easy|
You can’t perform that action at this time.
0 commit comments