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
Input: s = "2[bc]3[cd]ef"
Output: "bcbccdcdcdef"
Explanation: "2[bc]" becomes "bcbc", "3[cd]" becomes "cdcdcd",
and concatenating with "ef" gives "bcbccdcdcdef".
π 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
curr
string for building current segment.Track
num
for 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
num
times, 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,
curr
contains 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++)
class Solution {
public:
string decodedString(string& s) {
stack<pair<string, int>> st;
string curr = "";
int num = 0;
for (char c : s) {
if (isdigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '[') {
st.push({curr, num});
curr = "";
num = 0;
} else if (c == ']') {
auto [prev, cnt] = st.top();
st.pop();
string temp = curr;
for (int i = 1; i < cnt; i++) curr += temp;
curr = prev + curr;
} else {
curr += c;
}
}
return curr;
}
};
β Code (Java)
class Solution {
static String decodeString(String s) {
Stack<StringBuilder> stStr = new Stack<>();
Stack<Integer> stNum = new Stack<>();
StringBuilder curr = new StringBuilder();
int num = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '[') {
stStr.push(curr);
stNum.push(num);
curr = new StringBuilder();
num = 0;
} else if (c == ']') {
StringBuilder temp = curr;
curr = stStr.pop();
int cnt = stNum.pop();
while (cnt-- > 0) curr.append(temp);
} else {
curr.append(c);
}
}
return curr.toString();
}
}
π Code (Python)
class Solution:
def decodedString(self, s):
st_str, st_num = [], []
curr, num = "", 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c == '[':
st_str.append(curr)
st_num.append(num)
curr, num = "", 0
elif c == ']':
temp = curr
curr = st_str.pop()
cnt = st_num.pop()
curr += temp * cnt
else:
curr += c
return curr
π§ 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