SDE & MLE Prep

394. Decode String

Problem

Decode s, where k[text] means text repeated k times; brackets can be nested. The input is always well formed and digits only appear as repeat counts.

Example: "3[a]2[bc]" → "aaabcbc"; "3[a2[c]]" → "accaccacc"

On [ push (current string, repeat count) and reset; on ] pop and set cur = prev + cur * k.

3[a2[c]]
'3' k=3   '[' push ("",3)   'a' cur="a"
'2' k=2   '[' push ("a",2)  'c' cur="c"
']' cur = "a" + "c"*2 = "acc"
']' cur = ""  + "acc"*3 = "accaccacc"

Complexity: O(output length).

class Solution:
    def decodeString(self, s: str) -> str:
        st, cur, k = [], "", 0
        for ch in s:
            if ch.isdigit():
                k = k * 10 + int(ch)
            elif ch == "[":
                st.append((cur, k))
                cur, k = "", 0
            elif ch == "]":
                prev, times = st.pop()
                cur = prev + cur * times
            else:
                cur += ch
        return cur