Given an encoded string, return its decoded string. The encoding rule is: k[encoded_string]
, where the encoded_string
inside the square brackets is being repeated exactly k
times. You may assume that the input string is always valid; no extra white spaces, square brackets are well-formed, etc.
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
Example 3:
Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"
The problem contains nested structures and repeated patterns, which makes it apt for a stack based solution. Here is the strategy to decode the string:
10
).[
, start a new segment.]
, pop from stack until you get the matching [
, decode the current segment, and repeat it according to the number on the top of the stack before the [
.def decodeString(s: str) -> str:
stack = []
current_num = 0
current_string = ''
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
# Push the current num and string to the stack
stack.append(current_string)
stack.append(current_num)
# Reset current variables
current_string = ''
current_num = 0
elif char == ']':
# Pop the number first and then the string
num = stack.pop()
prev_string = stack.pop()
# Build the new string
current_string = prev_string + num * current_string
else:
current_string += char
return current_string
This solution efficiently handles the decoding of strings with nested and repeated encoded patterns using a stack-based approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?