Balance parenthesis in an alphanumeric string


  • 2
    B

    Given a string of parentheses and alphanumeric characters, return a valid balanced string.
    In a valid string for every opening/closing parentheses there is a matching closing/opening one.
    Example:
    Input: ab(a(c)fg)9)
    Possible valid output: ab(a()fg)9, another valid option might be: ab(a(c)fg9).

    The goal is to return a valid string in the most optimised way both memory and time vice.
    How can you use the fact that the string is alphanumeric?


  • 0
    M
    def balance(string):
        starting=['{','[','(']
        closing=['}',']',')']
        stack=[]
        for i in string:
            if i in starting:
                stack.append(i)
            if i in closing:
                x=stack.pop()
                if x!=starting[closing.index(i)]:
                    return False
    
        return True
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.