Snippets Collections
bool isValidParenthesis (string expression) {
  stack<char> s;
  for (int i = 0; i < expression.length(); i++) {
    char ch = expression[i];
    // if opening bracket push it to stack
    // if closing bracket, pop from stack, check if the popped element is the                 matching opening bracket
    if (ch == '(' || ch =='{' || ch == '[') {
      s.push(ch);
    }
    else {
      // for closing bracket
      if (!s.empty()) {
        char top = s.top();
        if ((ch == ')' && top == '(') || (ch == '}' && top == '{') || (ch == ']' &&               top == '[')) {
          s.pop();
        }
      }
      else {
        return false;
      }
    }
  }
  if (s.empty()) {
    return true;
  }
  else {
    return false;
  }
}
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

Sat Jul 20 2024 17:23:52 GMT+0000 (Coordinated Universal Time) https://youtu.be/BmZnJehDzyU?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

##c++ ##dsa ##loop ##algorithm #stack #parenthesis #validparenthesis
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