Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c4a7750

Browse files
committed
Add solution #394
1 parent 1c752e6 commit c4a7750

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

0394-decode-string.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@
181181
383|[Ransom Note](./0383-ransom-note.js)|Easy|
182182
387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy|
183183
392|[Is Subsequence](./0392-is-subsequence.js)|Easy|
184+
394|[Decode String](./0394-decode-string.js)|Medium|
184185
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|
185186
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|
186187
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|

0 commit comments

Comments
 (0)