Decode String Problem
Description
LeetCode Problem 394.
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. 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].
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"
Example 4:
Input: s = "abc3[cd]xyz"
Output: "abccdcdcdxyz"
Constraints:
- 1 <= s.length <= 30
- s consists of lowercase English letters, digits, and square brackets '[]'.
- s is guaranteed to be a valid input.
- All the integers in s are in the range [1, 300].
Solution
Approach: Two Stacks
Brackets can be nested, and an inner group must be expanded before the outer one that contains it. A stack handles this: when a [ opens, save what we have so far and start fresh; when the matching ] closes, expand the fresh part and glue it back onto what was saved.
Keep current, the text decoded since the last [, and count, the number being read. Then scan s:
- Digit:
count = count * 10 + digit. Numbers can have several digits (up to300), so do not assume one digit per count. [: pushcountonto a count stack andcurrentonto a prefix stack, then reset both:current = "",count = 0.]: pop the repeat count and the prefix, and setcurrent = prefix + current * repeat.- Letter: append it to
current.
At the end, current is the decoded string.
For "3[a2[c]]": at the inner [ the stacks hold (3, "") and (2, "a"). The first ] gives "a" + "c" * 2 = "acc", and the second gives "" + "acc" * 3 = "accaccacc".
Complexity: let n be the length of s and L the length of the decoded string. Each ] builds a string no longer than L, so the time is O(n · L) in the worst case. The space is O(n + L): the saved prefixes are separate pieces of the output.
class Solution:
def decodeString(self, s: str) -> str:
count_stack = [] # repeat counts of the open brackets
prefix_stack = [] # text decoded before each open bracket
current = "" # text decoded since the last open bracket
count = 0 # the number being read
for ch in s:
if ch.isdigit():
count = count * 10 + int(ch) # numbers can have several digits
elif ch == "[":
count_stack.append(count)
prefix_stack.append(current)
current = ""
count = 0
elif ch == "]":
repeat = count_stack.pop()
current = prefix_stack.pop() + current * repeat
else:
current += ch
return current
Now write it from memory
Close the write-up and solve it yourself against the tests.