Balanced Brackets

Sort by

recency

|

245 Discussions

|

  • + 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  
    
  • + 0 comments
    string isBalanced(string s) {
        unordered_map<char, char> map = {
            {'(', ')'},
            {'{', '}'},
            {'[', ']'}
        };
        
        stack<char> sc;
        for (char c : s) {
            if (map.count(c))
                sc.push(map[c]);
            else {
                if (sc.empty() || sc.top() != c)
                    return "NO";
                sc.pop();
            }
        }
        
        return (sc.empty()) ? "YES" : "NO";
    }
    
  • + 0 comments

    Python 3

    s = list(s)
        if len(s) % 2 != 0:
            return ('NO')
        char_dict = {"{":"}","[":"]",'(':')'}
        left_pt = 0
    
        while s != []:
            starting = s[left_pt]
            if starting not in char_dict.keys():
                return ('NO')
            target = char_dict[starting]
            if s[left_pt+1] == target:
                s.pop(left_pt)
                s.pop(left_pt)
                left_pt = 0
            else:
                left_pt += 1
                if left_pt == len(s)-1 and s != []:
                    return ('NO')
        return ('YES')
    
  • + 0 comments

    def isBalanced(s): stk = [] n = len(s) for i in range(n): if s[i] == '{' or s[i] == '[' or s[i] == '(': stk.append(s[i]) else: if (stk and ((s[i] == '}' and stk[-1] == '{') or (s[i] == ']' and stk[-1] == '[') or (s[i] == ')' and stk[-1] == '('))): stk.pop() else: return "NO" # unmatched closing bracket if stk: return "NO" else: return "YES"