831. Expand a compressed string with counts and nested groups
A compact format writes repeated text with counts. A count is a positive integer (it can have several digits) and applies only to the item right after it. An item is either one lowercase letter or a group in parentheses, and groups can nest. An item with no count appears once.
Write expand(s) that returns the fully expanded string. The input is always well formed.
def expand(s)Example 1
Input: expand("3b")
Output: "bbb"
Example 2
Input: expand("2a2(a3(b))")
Output: "aaabbbabbb": 2a gives "aa", the group a3(b) gives "abbb", and it repeats twice
Constraints
len(s)<= 200- Output length <= 100,000
- Input is well formed.
Hint 1
Read every digit before the item.
Hint 2
A "(" starts a recursive call that ends at the matching ")".
Hint 3
Default the count to 1.
Common mistakes
- Treating each digit as its own count, so "12x" becomes wrong.
- Applying a count to everything after it instead of only the next item.
- Forgetting to skip the closing parenthesis after a group.
Understand the idea
Nested repeat formats are parsed with recursion or an explicit stack. The key detail here is that a count binds only to the next item, so "2a2(a3(b))" means aa followed by two copies of (a followed by bbb). With a stack you push the current partial string and pending count on "(" and on ")" pop, repeat and append. Multi-digit counts must be built as count * 10 + digit.