Balanced Brackets

easy string stack

Problem

Given a string of bracket characters drawn from ( ) [ ] { }, decide whether every opening bracket has a matching closing bracket of the same kind, and that they are properly nested.

Example 1
Input"({[]})"
Outputtrue
Every opener is closed by its matching kind in the right order.
Example 2
Input"([)]"
Outputfalse
'(' and '[' interleave instead of nesting properly.

def is_balanced(s):
    match = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in '([{':
            stack.append(ch)
        else:
            if not stack or stack.pop() != match[ch]:
                return False
    return not stack
function isBalanced(s) {
  const match = { ')': '(', ']': '[', '}': '{' };
  const stack = [];
  for (const ch of s) {
    if (ch === '(' || ch === '[' || ch === '{') {
      stack.push(ch);
    } else {
      if (stack.pop() !== match[ch]) return false;
    }
  }
  return stack.length === 0;
}
class Solution {
    public boolean isBalanced(String s) {
        Map<Character, Character> match = Map.of(')', '(', ']', '[', '}', '{');
        Deque<Character> stack = new ArrayDeque<>();
        for (char ch : s.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else {
                if (stack.isEmpty() || stack.pop() != match.get(ch)) return false;
            }
        }
        return stack.isEmpty();
    }
}
bool isBalanced(string s) {
    unordered_map<char, char> match = {{')', '('}, {']', '['}, {'}', '{'}};
    stack<char> st;
    for (char ch : s) {
        if (ch == '(' || ch == '[' || ch == '{') {
            st.push(ch);
        } else {
            if (st.empty() || st.top() != match[ch]) return false;
            st.pop();
        }
    }
    return st.empty();
}
Time: O(n) Space: O(n)