AlgoMaster Logo

Decode String

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

In this approach, we use recursion to decode the string. The idea is to iterate through the string and whenever an opening bracket '[' is encountered, we recursively decode the string within the brackets and repeat it the specified number of times. This is tracked via a counter. Each recursive call handles a part of the string enclosed in square brackets.

Steps:

  1. Initialize a global index to track the position in the string.
  2. Iterate over the string and for each character:
    • If it's a digit, build the multiplier (k=2 or 12, etc.).
    • If it's '[', recursively decode the substring that follows.
    • If it’s ']', return the accumulated string up to this point.
    • If it's a letter, append it to the result string.
  3. This approach is accomplished by a helper method that performs the recursion and returns the decoded substring.

Code:

2. Iterative Approach using Stacks

Intuition:

Instead of using recursion, you can use stacks to simulate the process. Use two stacks: one to store numbers (multiplier) and another to store current encoded string segments. Traverse through the string, upon encountering '[', push the current result and multiplier onto the stacks and reset them. When ']' is encountered, pop from the stacks to get the last string and multiplier, concatenate the result.

Steps:

  1. Traverse through the input string and perform the following:
    • If a number is found, compute the full number (multiplier) using a loop.
    • If '[', push the current string and multiplier on stacks.
    • If ']', pop from the stacks and append the current string.
    • If it's a character, append it to the current result string.
  2. Concatenate results as needed upon encountering ']' and continue until end.

Code: