# Reverse Parenthesis # Given a string that contains properly nested parentheses, # return the decoded version of the string using the following rules: # # All characters inside each pair of parentheses should be reversed. # Parentheses should be removed from the final result. # If parentheses are nested, the innermost pair should be reversed first, # and then its result should be included in the reversal of the outer pair. # Assume all parentheses are evenly balanced and correctly nested. def decode(char_str: str) -> str: # Use a stack to process characters and handle nested parentheses stack = [] for char in char_str: # When we hit a closing parenthesis, we need to # extract and process the substring inside it if char == ')': buffer = [] # Pop characters until we find the matching '(' # This collects the substring *in reverse order*, # because stack.pop() removes from the end. while stack and stack[-1] != '(': buffer.append(stack.pop()) # Remove the '(' from the stack stack.pop() # Push the reversed substring back onto the stack. # Note: the contents of 'buffer' are already reversed # relative to their original order, so extending the stack # with 'buffer' effectively performs the reversal required # for this decode operation. for c in buffer: stack.append(c) else: # For normal characters, just push them onto the stack. # Opening parentheses '(' also get pushed until we find a ')'. stack.append(char) # Join everything in the stack to form the decoded string return ''.join(stack) def check(status): print("PASS" if status else "FAIL") check(decode("(f(b(dc)e)a)") == "abcdef") check(decode("((is?)(a(t d)h)e(n y( uo)r)aC)") == "Can you read this?") check(decode("f(Ce(re))o((e(aC)m)d)p") == "freeCodeCamp")