Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Decode String

LeetCode #394Medium
k[body] with nesting · "]" collapses the top

Given an encoded string using the rule k[encoded] meaning the bracketed substring is repeated k times, return the fully decoded string. Encodings may be nested.

Asked atGoogleAmazonMeta
step 1 / 19
3
[
a
2
[
c
]
]
[0][1][2][3][4][5][6][7]
current string
3
[
a
2
[
c
]
]
[0][1][2][3][4][5][6][7]
Brute force · expand innermost repeatedly
1given s
2while s contains "[":
3 find the innermost k[body]
4 replace it with body repeated k times
5return s
state
  • s"3[a2[c]]"

line 1Decode k[body] = body repeated k times — and bodies can nest. First idea: the INNERMOST brackets contain no nesting, so expand them first, then repeat.