Balanced Brackets

Sort by

recency

|

248 Discussions

|

  • + 0 comments
    
    
    stack<char> Brackets;
    for(char c : s)
    {
        if(c == '(' || c == '[' || c == '{')
            Brackets.push(c);
        else 
        {
    
            if(Brackets.empty()) return "NO";
            char top = Brackets.top();
            if((c == ')' && top != '(')
            || (c == ']' && top != '[')
            || (c == '}' && top != '{'))
                return "NO";
            else 
                Brackets.pop();   
        }
    }
            return Brackets.empty() ? "YES" : "NO";
    

    }

  • + 0 comments

    The thing to understand is that at any step, when a closing bracket is met, it must be a match for the last encountered opening bracket. Using a stack to track expected next closing bracket does the job .

  • + 0 comments
    def isBalanced(s):
        # Write your code here
        open_bracket = "{[("
        enclose_bracket = "}])"
        pairs = ["{}", "[]", "()"]
        
        if len(s) % 2 != 0:
            return "NO"
        
        if s[0] in enclose_bracket or s[-1] in open_bracket:
            return "NO"
        
        stack = []
        for p in s:
            if p in open_bracket:
                stack.append(p)
            else:
                if len(stack) == 0:
                    return "NO"
                    
                pair = stack.pop() + p
                if pair not in pairs:
                    return "NO"
        
        return "YES"
    
  • + 0 comments
    string isBalanced(string s) {
    stack<char> stk;
    
    
    for (int i = 0 ; i<s.length(); i++) 
    {
    if(!stk.empty())
    {
    char tp  =stk.top();
    
    if( (tp == '{' && s[i] == '}')||(tp == '(' && s[i] == ')') ||( tp == '[' && s[i] == ']'))
    {
    stk.pop();
    
    }else {
    stk.push(s[i]);
    }
    }else {
    stk.push(s[i]);
    
    }
    
    }
    
  • + 1 comment

    Python:

    def isBalanced(s):
        left, right = ["(", "{", "["], [")", "}", "]"]
        stack = []
        for char in s:
            # add opening brackets to the stack
            if char in left:
                stack.append(char)
            # if it's a right bracket:
            else:       
                # closing bracket appears without an opening bracket
                if not stack:
                    return "NO"     
                # check the last opening bracket in the stack
                idx = right.index(char) 
                if stack.pop() == left[idx]:    # remove last bracket in-place
                    continue
                return "NO"    # closing bracket didn't find an opening match
        return "NO" if stack else "YES"     # "YES" if stack is empty