Date and Time: Oct 17, 2024, 14:07 (EST)
Link: https://leetcode.com/problems/decode-string/
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; there are 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 will not be input like 3a or 2[4].
The test cases are generated so that the length of the output will never exceed 10^5.
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"
-
1 <= s.length <= 30 -
sconsists of lowercase English letters, digits, and square brackets'[]'. -
sis guaranteed to be a valid input. -
All the integers in
sare in the range[1, 300].
Add each char from s into stack[] except i == "]". When we have "]", we first get the subStr by popping from the stack, then get the digits for how many times we need to repeat this subStr, and we append this repeated subStr into stack[] again, so when we have nested square brackets happen, we can repeat the subStr. Finall, concatenate all subStrs from stack[] and return.
May 28, 2026, [Time Taken 45m 29s]
class Solution:
def decodeString(self, s: str) -> str:
# Save num of time to repeat, and the string to repeat in stack
# When i == ']', retrieve the string from stack until '['
# Pop the '['
# Retrieve the number
# Append into res"" by int(digit) * char
# TC: O(n), n=len(s), SC: O(n)
res = ""
stack = []
for i in s:
if i != "]":
stack.append(i)
else:
# Retrieve the string
string = ""
while stack[-1] != "[":
string = stack.pop() + string
stack.pop() # to remove '['
# Retrieve the number
digit = ""
while stack and stack[-1].isdigit():
digit = stack.pop() + digit
# Update stack with the latest string
stack.append(int(digit) * string)
# Join all the string and return
return "".join(stack)Time Complexity:
Space Complexity: