Snippets Collections
def generateParenthesis(n):
    #only add parentehsis if openN < n 
    #only add close parenthesis if closeN < openN 
    #valid if open == closed == n 

    stack = []
    res = []
    
    def backtrack(openN, closeN): 
        if openN == closeN == n: 
            res.append("".join(stack))
            return 
        if openN < n: 
            stack.append('(')
            backtrack(openN + 1, closeN)
            stack.pop()
        if closeN < openN: 
            stack.append(")")
            backtrack(openN, closeN + 1)
            stack.pop()
        #stack.pop() is necessary to clean up stack and come up with other solutions 
        
    backtrack(0, 0)
    #concept is you build openN, closeN but initially, they are at 0 
    return res 

generateParenthesis(3)
def parenthesis(string):
    openchr = { 
        '(' : 0,
        '{' : 1,
        '[' : 2
    }
    closechr = { 
        ')' : 0,
        '}' : 1,
        ']' : 2
    }
    visited = []
    
    for char in string:
        if char in openchr:
            visited.append(char)
        else:
            if len(visited) == 0:
                return False
            popped = visited.pop(-1)
            if (openchr[popped] != closechr[char]):
                return False

    if len(visited) == 0:
        return True
    return False
star

Tue Sep 27 2022 02:03:10 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/generate-parentheses/

#python #neetcode #parenthesis #open #close
star

Mon Feb 21 2022 00:01:45 GMT+0000 (Coordinated Universal Time)

#python #parenthesis #checker

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension