Balanced Brackets

Sort by

recency

|

40 Discussions

|

  • + 0 comments

    Java O(n)

    public static String isBalanced(String s) {
            Stack<Character> stack = new Stack<>();
    
            for (char c : s.toCharArray()) {
                if (c == '(' || c == '{' || c == '[') {
                    stack.push(c);
                } else {
                    if (stack.isEmpty()) {
                        return "NO";
                    }
                    char top = stack.pop(); 
                    if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
                        return "NO";
                    }
                }
            }
            return stack.isEmpty() ? "YES" : "NO";
        }
    
  • + 0 comments

    Java 15

    var squareOpen = false;
    var curlyOpen = false;
    var parenthesisOpen = false;
    
    Queue<Character> brackets = new LinkedList<>();
    Stack<Character> expectedClosures = new Stack<>();
    for (var c : s.toCharArray()) {
    	brackets.add(c);
    }
    
    while (!brackets.isEmpty()) {
    	var ele = brackets.poll();
    	try {
    		switch (ele) {
    			case '[': squareOpen = true; expectedClosures.add(']'); break;
    			case '(': parenthesisOpen = true; expectedClosures.add(')'); break;
    			case '{': curlyOpen = true; expectedClosures.add('}'); break;
    			case ']': squareOpen = false; if (expectedClosures.pop() != ele) return "NO"; break;
    			case ')': parenthesisOpen = false; if (expectedClosures.pop() != ele) return "NO"; break;
    			case '}': curlyOpen = false; if (expectedClosures.pop() != ele) return "NO";
    		}
    	} catch (EmptyStackException ex) {
    		return "NO";
    	}
    }
    return !squareOpen && !parenthesisOpen && !curlyOpen ? "YES" : "NO";
    
  • + 0 comments

    JS

    function isBalanced(string) {
        const pairs = new Map([[")", "("], ["}", "{"], ["]", "["]]);
        const brackets = [];
        let balanced = true;
        for (let bracket of string) {
            if (pairs.has(bracket)) {
                if (brackets.pop() != pairs.get(bracket)) {
                    balanced = false;
                    break;
                }
            }
            else {
                brackets.push(bracket);
            }
        }
        return (balanced && brackets.length == 0) ? "YES" : "NO";
    }
    
  • + 0 comments

    C#

    char last = ' ';
      for (int i = 0;i<s.Length;i++) 
      {
        char c = s[i];
        switch (c) 
        {
          case '{':
            break;
          case '[':
            break;
          case '(':
            break;
          case ')':
            if (last=='(') 
            {
              s = s.Remove(i - 1, 2);
              i -= 2;
            }
            else 
            {
              return "NO";
            }
            break;
          case ']':
            if (last == '[')
            {
              s = s.Remove(i - 1, 2);
              i -= 2;
            }
            else
            {
              return "NO";
            }
            break;
          case '}':
            if (last == '{')
            {
              s = s.Remove(i - 1, 2);
              i -= 2;
            }
            else
            {
              return "NO";
            }
            break;
        }
          if (i>-1) 
        {
          last = s[i];
        }     
        else 
        {
          last = ' ';
        }
      }
    
      if (s.Length==0) 
      {
        return "YES";
      }
      else 
      {
        return "NO";
      }
    
  • + 0 comments

    Python

    def getKey(c):
        if(c == '{'): return 1
        if(c == '}'): return 2
        if(c == '('): return 3
        if(c == ')'): return 4
        if(c == '['): return 5
        if(c == ']'): return 6
    
        
    def isBalanced(s):
        # Write your code here
        arrCharacter  = list(s)
        stack = []
        for x in arrCharacter:
            if(len(stack)==0 or getKey(x) != 1+getKey(stack[-1])):
                stack.append(x)
            else:
                stack.pop()
        print(stack)
        return "YES" if len(stack)==0 else "NO"