Menu
CoddyTech

Decode String

An encoded string writes repeated text as k[text], which stands for text written k times in a row. Groups can sit inside other groups, so 2[a3[b]] stands for abbbabbb. Write a function that gets an encoded string s and returns the decoded string.

Letters outside every bracket stay as they are. Each count is a positive whole number written right before its [, and digits appear nowhere else.

Function

decodeString(s: string) → string
sstring
the encoded string
Returnsstring
the decoded string

Constraints

  • 1 ≤ s.length ≤ 104
  • s contains only lowercase English letters, digits, [ and ].
  • s is a valid encoding: every [ follows a count and has a matching ], and no brackets are empty.
  • Every count k satisfies 1 ≤ k ≤ 300 and has no leading zero.
  • Brackets nest at most 100 levels deep.
  • The decoded string has at most 5 × 104 characters.

Examples

Input
s = "2[ab]3[c]x"
Output
"ababcccx"
Explanation
2[ab] gives abab and 3[c] gives ccc. The x sits outside every bracket, so it is copied as it is, which gives ababcccx.

lock icon+22 hidden tests on Submit

challenge icon

Follow-up

The decoded string can be far longer than the input. How would you return only the character at position i of the decoded string, without building it, when the decoded length can reach 10^18?

Reset code
def decodeString(s):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

s = "2[ab]3[c]x"

Expected

"ababcccx"