Skip to main content
Back to problems
Leetcode
decode-string
Medium
Stacks
Recursion
String Processing
Decode String

Decode an encoded string where patterns of the form k[encodedstring]k[encoded_string] repeat the enclosed substring kk times.

Acceptance 0%
Problem Statement
Core description from the backend problem record.

Description

Given an encoded string, return its decoded string.

The encoding rule is: k[encodedstring]k[encoded_string], where the

clike

encoded_string
inside the square brackets is being repeated exactly kk times.

clike

$k$
is guaranteed to be a positive integer.

You may assume that the input string is always valid; no extra white spaces, square brackets are well-formed, and no invalid characters are present. The original data does not contain any digits and digits are only for those repeat numbers, kk. For example, there will not be an input like

clike

3a
or

clike

2[4]
.

The decoded string may be long, but it is guaranteed to fit in a 32-bit signed integer length.

Input Format

A single encoded string ss.

Output Format

Return the decoded string.

Constraints

  • The input string is valid.
  • Digits appear only as repeat counts kk.
  • The decoded result fits in a 32-bit signed integer length.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "3[a]2[bc]"

Output

"aaabcbc"

Explanation

clike

3[a]
becomes

clike

aaa
, and

clike

2[bc]
becomes

clike

bcbc
. Concatenating them gives

clike

aaabcbc
.

Example 2

Input

s = "3[a2[c]]"

Output

"accaccacc"

Explanation

Inner

clike

2[c]
becomes

clike

cc
, so

clike

3[a2[c]]
becomes

clike

3[acc]
which is

clike

accaccacc
.

Show 1 more example

Example 3

Input

s = "2[abc]3[cd]ef"

Output

"abcabccdcdcdef"

Explanation

clike

2[abc]
becomes

clike

abcabc
,

clike

3[cd]
becomes

clike

cdcdcd
, then append

clike

ef
.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.