I am trying to solve 394. Decode String on Leetcode, this was my solution (I know it’s inefficient):
class Solution:
def decodeString(self, s: str) -> str:
# using recursion
stack = []
for ch in s:
if ch != ']':
stack.append(ch)
else:
new_s = ''
while stack[-1] != '[':
new_s += stack.pop()
new_s = new_s[::-1]
stack.pop()
number = ''
while stack and stack[-1].isdigit():
print(stack[-1])
number += stack.pop()
number = int(number[::-1])
print(new_s)
stack.append(number * new_s)
return "".join(stack)
and this is the working solution:
class Solution:
def decodeString(self, s: str) -> str:
stack = []
for ch in s:
if ch != ']':
stack.append(ch)
else:
# Collect the characters forming the encoded string
decoded_string = []
while stack[-1] != '[':
decoded_string.append(stack.pop())
stack.pop() # Remove the '['
# Now reverse the decoded string to get the correct order
decoded_string = ''.join(decoded_string[::-1])
# Get the number (how many times to repeat)
number = []
while stack and stack[-1].isdigit():
number.append(stack.pop())
number = int(''.join(number[::-1]))
# Append the repeated decoded string back to the stack
stack.append(number * decoded_string)
return "".join(stack)
Why is the first function not working? I really think that there is no difference except that I am reversing a string, and the correct code reverses the list.
Idk what to say here except that I just don’t see why one algo works and the other doesn’t…
New contributor
1