Decode String

Given an encoded string s, return its decoded string.

The encoding rule is k[encoded_string], where the encoded_string inside the square brackets is repeated exactly k times. The value k is guaranteed to be a positive integer.

You may assume that the input string is always valid:

  • There are no extra white spaces.
  • Square brackets are well-formed.
  • The original data does not contain any digits.
  • Digits are only used for repeat numbers k; for example, inputs like 3a or 2[4] will not occur.

The test cases are generated so that the length of the output will never exceed 10^5.

Example 1
Inputs = "3[a]2[bc]"
Output"aaabcbc"
The substring a is repeated 3 times and bc is repeated 2 times, producing aaabcbc.
Example 2
Inputs = "3[a2[c]]"
Output"accaccacc"
The nested substring c is repeated 2 times inside a2[c], and the resulting acc is repeated 3 times.

Constraints

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets '[]'.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

Asked at 39 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate