17. Decode the String
β GFG solution to the Decode the String problem: expand encoded patterns k[substring] using stack-based approach for nested bracket handling. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given an encoded string s, decode it by expanding the pattern k[substring], where the substring inside brackets is written k times. k is guaranteed to be a positive integer, and the encoded string contains only lowercase English alphabets and digits. Return the final decoded string.
The test cases are generated so that the length of the output string will never exceed $10^5$.
π Examples
Example 1
Input: s = "3[b2[ca]]"
Output: "bcacabcacabcaca"
Explanation: Inner substring "2[ca]" breaks down into "caca".
Now, new string becomes "3[bcaca]"
Similarly "3[bcaca]" becomes "bcacabcacabcaca" which is the final result.Example 2
Input: s = "3[ab]"
Output: "ababab"
Explanation: The substring "ab" is repeated 3 times giving "ababab".Example 3
π Constraints
$1 \le |s| \le 10^5$
$1 \le k \le 100$
β
My Approach
The optimal approach uses a Stack to handle nested bracket structures and decode patterns from inside out:
Stack-Based Decoding
Initialize Data Structures:
Use a stack of pairs to store
{current_string, repeat_count}.Maintain
currstring for building current segment.Track
numfor parsing repeat counts.
Process Each Character:
Digit: Build the repeat count by multiplying by 10 and adding current digit.
Opening Bracket '[' : Push current state
{curr, num}to stack, reset variables.Closing Bracket ']' : Pop from stack, repeat current string
numtimes, and append to previous string.Letter: Simply append to current string.
Handle Nested Patterns:
Stack naturally handles nested brackets by processing innermost patterns first.
Each closing bracket resolves one level of nesting.
Return Result:
After processing all characters,
currcontains the fully decoded string.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the input string. Each character is processed exactly once, and string operations are amortized constant time.
Expected Auxiliary Space Complexity: O(d Γ m), where d is the maximum depth of nested brackets and m is the average length of strings at each level. In the worst case, this is O(n) where all characters could be stored in the stack.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated