




Sponsored
Sponsored
This approach uses a stack to decode the string iteratively. Each time we encounter a '[', we push the current accumulated string and the current repetition number to the stack. When we encounter a ']', we pop from the stack, retrieve the last accumulated string and repeat the current decoded substring accordingly.
Time Complexity: O(n), where n is the length of the input string, since we scan through the string linearly while utilizing stack operations.
Space Complexity: O(n), due to the stacks used to keep track of numbers and strings.
1using System;
2using System.Collections.Generic;
3
4class DecodeStringClass {
5    public static string DecodeString(string s) {
6        Stack<int> countStack = new Stack<int>();
7        Stack<string> resultStack = new Stack<string>();
8        string result = "";
9        int index = 0;
10        
11        while (index < s.Length) {
12            if (char.IsDigit(s[index])) {
13                int count = 0;
14                while (char.IsDigit(s[index])) {
15                    count = count * 10 + (s[index] - '0');
16                    index++;
17                }
18                countStack.Push(count);
19            } else if (s[index] == '[') {
20                resultStack.Push(result);
21                result = "";
22                index++;
23            } else if (s[index] == ']') {
24                string temp = resultStack.Pop();
25                int repeatTimes = countStack.Pop();
26                for (int i = 0; i < repeatTimes; i++) {
27                    temp += result;
28                }
29                result = temp;
30                index++;
31            } else {
32                result += s[index];
33                index++;
34            }
35        }
36        return result;
37    }
38
39    static void Main(string[] args) {
40        string s = "3[a2[c]]";
41        Console.WriteLine(DecodeString(s));
42    }
43}
44This C# solution leverages stacks to handle nested encoding structures iteratively. A continuous string building and integer tracking occur as chars from the input string process, leveraging brackets for structure control, soon representing the expanded string version.
This approach uses recursion to decode the string. The function processes the string, and upon encountering a '[', it recursively decodes the repeating substring. This allows elegant handling of nested encoded strings by delegating responsibility to sub-problems.
Time Complexity: O(n), with n as length of string, since recursive steps are based on string length.
Space Complexity: O(n), mainly for recursive call stack and intermediate storage.
1
In this Java solution, recursive strategies parse through the original string input, leveraging a secondary method that iterates when new bracketed sequences arise. Post inner-depth resolutions, the subdivisions are repeated and integrated back into broader levels.