class Solution:
def decodeString(self, s: str) -> str:
stack = []
curr_num = 0
curr_str = ""
for c in s:
if c.isdigit():
curr_num = curr_num * 10 + int(c)
elif c == "[":
stack.append((curr_str, curr_num))
curr_str = ""
curr_num = 0
elif c == "]":
last_str, num = stack.pop()
curr_str = last_str + curr_str * num
else:
curr_str += c
return curr_str
class Solution {
public:
string decodeString(string s) {
stack> stk;
string curr_str = "";
int curr_num = 0;
for (char c : s) {
if (isdigit(c)) {
curr_num = curr_num * 10 + (c - '0');
} else if (c == '[') {
stk.push({curr_str, curr_num});
curr_str = "";
curr_num = 0;
} else if (c == ']') {
auto p = stk.top(); stk.pop();
string temp = "";
for (int i = 0; i < p.second; ++i) temp += curr_str;
curr_str = p.first + temp;
} else {
curr_str += c;
}
}
return curr_str;
}
};
class Solution {
public String decodeString(String s) {
Stack<String> strStack = new Stack<>();
Stack<Integer> numStack = new Stack<>();
String currStr = "";
int currNum = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
currNum = currNum * 10 + (c - '0');
} else if (c == '[') {
strStack.push(currStr);
numStack.push(currNum);
currStr = "";
currNum = 0;
} else if (c == ']') {
StringBuilder temp = new StringBuilder();
int repeat = numStack.pop();
for (int i = 0; i < repeat; i++) temp.append(currStr);
currStr = strStack.pop() + temp.toString();
} else {
currStr += c;
}
}
return currStr;
}
}
var decodeString = function(s) {
let stack = [];
let currStr = "";
let currNum = 0;
for (let c of s) {
if (!isNaN(c) && c !== ' ') {
currNum = currNum * 10 + Number(c);
} else if (c === "[") {
stack.push([currStr, currNum]);
currStr = "";
currNum = 0;
} else if (c === "]") {
let [lastStr, num] = stack.pop();
currStr = lastStr + currStr.repeat(num);
} else {
currStr += c;
}
}
return currStr;
};
The Decode String problem asks you to decode a specially formatted input string s
according to the following rules:
3[a]
means "repeat 'a' three times", resulting in aaa
.2[abc3[cd]ef]
.s
consists of digits, letters, and square brackets, and is always a valid encoding (no malformed brackets or numbers).s
and return the resulting string.Constraints:
s.length
≤ 30,000s
contains only digits, English letters, '['
, and ']'
At first glance, this problem looks similar to parsing mathematical expressions with parentheses, but with the twist that numbers now indicate repetition. A brute-force approach might try to repeatedly find the innermost brackets and expand them, but this would be inefficient and hard to manage for deeply nested strings.
To handle nested repetition, we need a way to keep track of what we're currently building and how many times to repeat it. Stacks are a natural fit for this, since they help us remember the context as we descend into deeper nested structures and then "pop" back out as we finish each one.
The main idea is to process the string character by character, using a stack to remember the current string and repeat count whenever we enter a new bracketed section. When we hit a closing bracket, we pop the stack, repeat the string, and append it to the previous context.
s
:
'['
:
']'
:
We use a stack because it allows us to easily "go back" to the previous context whenever we finish decoding a nested section. This approach works efficiently even for deeply nested or long input strings.
Let's walk through the example s = "3[a2[c]]"
:
The final decoded string is accaccacc
.
The Decode String problem is elegantly solved by using a stack to manage nested repetitions. By carefully tracking the current string and repeat count at each level, we can efficiently and cleanly decode even complex nested encodings in a single pass. The stack-based approach is both intuitive and optimal, making it a great example of how classic data structures can simplify seemingly complex parsing tasks.