




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.
The JavaScript solution uses stacks to track numbers and intermediary strings. It builds the final decoded string by iteratively handling characters in accordance with bracket positions, numbers, and plain string elements, affecting the emerging string with repeated and concatenated patterns.
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#include <iostream>
2#include <string>
3
4class Solution {
5public:
6    std::string decodeString(const std::string &s, int &i) {
7        std::string result = "";
8
9        while (i < s.length() && s[i] != ']') {
10            if (!isdigit(s[i])) {
11                result += s[i++];
12            } else {
13                int n = 0;
14                while (i < s.length() && isdigit(s[i])) {
15                    n = n * 10 + s[i++] - '0';
16                }
17
18                i++;  // skipping the '['
19                std::string decodedString = decodeString(s, i);
20                i++;  // skipping the ']'
21
22                while (n-- > 0) result += decodedString;
23            }
24        }
25
26        return result;
27    }
28
29    std::string decodeString(const std::string &s) {
30        int i = 0;
31        return decodeString(s, i);
32    }
33};
34
35int main() {
36    Solution sol;
37    std::string s = "3[a2[c]]";
38    std::cout << sol.decodeString(s) << std::endl;
39    return 0;
40}In the C++ recursive solution, we employ a helper function that picks up parsing from varying points correlating with where '[' and ']' delimit sequences. The recursion effectively tackles nested cases by delving into deeper levels for fully formed decoded segments that then merge upwards.