# 394. Decode String

Given an encoded string, return it's decoded string.

The encoding rule is: `k[encoded_string]`, where the encoded\_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like `3a` or `2[4]`.

**Examples:**

```
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
```

```cpp
// Recursion
string decodeHelper(const string& s, int& i) {
    string res;
    while (i < s.length() && s[i] != ']') {
        // add character directly
        if (s[i] < '0' || s[i] > '9') {
            res += s[i++];
        } else {
            int num = 0;
            while (s[i] >= '0' && s[i] <= '9') {
                num = num * 10 + (s[i++] - '0');
            }
            ++i; // Skip '['
            string tmp = decodeHelper(s, i);
            ++i; // Skip ']'
            while (num-- > 0) {
                res += tmp; 
            }
        }
    }
    return res;
}
string decodeString(string s) { // time: O(n); space: O(n)
    int i = 0;
    return decodeHelper(s, i);
}
```

```cpp
// Iteration
string decodeString(string s) { // time: O(n); space: O(n)
    string str;
    int num = 0;
    stack<int> st_num;
    stack<string> st_str;
    for (int i = 0; i < s.length(); ++i) {
        if (s[i] >= '0' && s[i] <= '9') {
            num = num * 10 + (s[i] - '0');
        } else if (s[i] == '[') {
            st_num.push(num);
            num = 0;
            st_str.push(str);
            str.clear();
        } else if (s[i] == ']') {
            int k = st_num.top(); st_num.pop();
            while (k-- > 0) {
                st_str.top() += str;
            }
            str = st_str.top(); st_str.pop();
        } else { // s[i] is char
            str += s[i];
        }
    }
    return str;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/dfs-and-bfs/394.-decode-string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
