Balanced Brackets

Sort by

recency

|

237 Discussions

|

  • + 0 comments

    My Java solution:

    public static String isBalanced(String s) {
            
            Stack<Character> stack = new Stack<>();
            HashMap<Character, Character> map = new HashMap<>();
            map.put(')', '(');
            map.put(']', '[');
            map.put('}', '{');
            
            // \ ({}) \     \ )({}) \
            for (char c : s.toCharArray()) {
                if (map.containsKey(c)) {
                    if (!stack.isEmpty() && stack.peek() == map.get(c)) {
                        stack.pop();
                    } else {
                        return "NO";
                    }
                } else {
                    stack.push(c);
                }
            }
            
            return (stack.isEmpty()) ? "YES" : "NO";
        }
    
  • + 0 comments

    This is my python solution. It's consise and self explanatory if you understand the application of a stack.

    def isBalanced(s):
        stack = []
        open_to_close = {"{": "}", "[": "]", "(": ")"}
        for bracket in s:
            # Open bracket case
            closing_bracket = open_to_close.get(bracket)
            if closing_bracket:
                stack.append(closing_bracket)
            # Close bracket case
            elif not stack or bracket != stack.pop():
                return "NO"
        
        # If we have looped through the entire string and the stack is empty, all opening brackets were closed
        return "NO" if stack else "YES"
    
  • + 0 comments

    JS solution:

    function isBalanced(s) {
        if (s.length % 2 != 0) return "NO"
        const PAIRS = {
            "}": "{",
            "]": "[",
            ")": "("
        }
        const brackets = []
    
        for (let i = 0; i < s.length; i++) {
            if (!(s[i] in PAIRS)) {
                brackets.push(s[i])
            } else {
                let counterBracket = brackets.pop()
                if (PAIRS[s[i]] !== counterBracket) brackets.push(null)     
            }
        }
        return brackets.length > 0 ? "NO" : "YES"
    }
    
  • + 1 comment

    Python solution:

    My solution avoids to read types of brackets:

    -opening brackets have even values

    -closing brackets have odd values next to the corresponding opening bracket We then just need to check that an odd value doesn't fill an empty stack or that there is no even value in the stack different from the expected one.

    def isBalanced(s):
        if len(s) % 2 != 0:
            return "NO"
        mydict = {}
        mydict["{"] = 0
        mydict["}"] = 1
        mydict["["] = 2
        mydict["]"] = 3
        mydict["("] = 4
        mydict[")"] = 5
        line = []
        for ind in range(len(s)):
            if mydict[s[ind]] % 2 == 0:
                line.append(mydict[s[ind]])
                continue
            if not line:
                return "NO"
            for ind2, elem in enumerate(line[::-1]):
                if elem == mydict[s[ind]] - 1:
                    line.pop(- 1 - ind2)
                    break
                else:
                    if elem % 2 == 0:
                        return "NO"
        if line:
            return "NO"
        return "YES"
    
  • + 0 comments

    C++ O(n)

    the idea:

    • each time you encounter an opening bracket, push it to the stack. each time you encounter a closing bracket, check if the opening bracket at the top of the stack matches the closing bracket, if so, pop the stack.
    • to prevent segmentation fault in case of encountring a closing bracket with an empty stack, simply return NO. this would for example here: }(){

    The code:

    string isBalanced(string s) {
        stack<char> stk;
        char top;
        for(char c : s){
            if(c == '(' || c == '[' || c == '{')
                stk.push(c);
    						
            if(c == ')' || c == ']' || c == '}'){
                if(stk.empty()) return "NO";
                top = stk.top();
    						
                if(c == ')' && top == '(' || c == ']' && top == '[' || c == '}' && top == '{')
                    stk.pop();
    								
                else
                 return "NO";
            }
                 
        }
        return stk.empty() ? "YES" : "NO";
    }