




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.
1#include <iostream>
2#include <string>
3#include <stack>
4
5std::string decodeString(const std::string& s) {
6    std::stack<int> numStack;
7    std::stack<std::string> strStack;
8    std::string result = "";
9    int num = 0;
10    
11    for (char c : s) {
12        if (isdigit(c)) {
13            num = num * 10 + (c - '0');
14        } else if (c == '[') {
15            numStack.push(num);
16            strStack.push(result);
17            result = "";
18            num = 0;
19        } else if (c == ']') {
20            std::string temp = result;
21            int repeatTimes = numStack.top(); numStack.pop();
22            result = strStack.top(); strStack.pop();
23            while (repeatTimes--) result += temp;
24        } else {
25            result += c;
26        }
27    }
28    return result;
29}
30
31int main() {
32    std::string s = "3[a2[c]]";
33    std::cout << decodeString(s) << std::endl;
34    return 0;
35}In this C++ solution, two stacks are utilized: one for numbers to record repetition factors and another for strings to store intermediate results. As the algorithm parses through the characters of the string, it determines when to push onto or pop from the stacks, consequently building the decoded string iteratively.
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.