Posted on:

17 Nov 2023

0

Same approach but with the opening braquets as keys in the dict.

the main benefit is in the IF. If you don't meet the 2 valid options, you can directly return False, no need to continue .

def check(string):
    stack = []
    
    d = {"{":"}", "(":")", "[":"]"}
    
    for char in string:
        if char in d:
            stack.append(char)
        elif stack and char == d[stack[-1]]:
            stack.pop()
        else:
            return False
        
    return not stack

0 answers ( 0 marked as helpful)

Submit an answer