Sobes.tech
Senior

/*Given a string, implement a function to check the correctness of bracket notation. Each opening bracket must have a corresponding closing bracket. Opening and closing brackets must be in the correct order. Types of brackets: "{", "}", "(", ")", "[", "]". Input: "([]){}[(()())()]" Result: true Input: "[(])" Result: false Because brackets 2 and 3 are incorrect, the closing ']' appears before the closing '('.*/ public boolean check(String s){ Deque<Character> stack = new ArrayDeque<>(); Map<Character, Character> map = Map.of( ')', '(', ']', '[', '}', '{' ); // ((( for( char c : s.toCharArray()){ if(map.containsValue(c)){ stack.push(c); } else if(map.containsKey(c)){ if( stack.isEmpty() || stack.pop() != map.get(c)){ return false; } } } return stack.isEmpty(); }

sobes.tech AI

Answer from AI

The proposed function in Java correctly checks the correctness of bracket placement using a stack and mapping closing brackets to their corresponding opening brackets.

Main idea:

  • When encountering an opening bracket, push it onto the stack.
  • When encountering a closing bracket, check that the top element of the stack matches it.
  • If there is no match or the stack is empty, return false.
  • At the end, check that the stack is empty (all brackets are closed).

Example implementation in Kotlin:

fun check(s: String): Boolean {
    val stack = ArrayDeque<Char>()
    val map = mapOf(')' to '(', ']' to '[', '}' to '{')

    for (c in s) {
        if (c in map.values) {
            stack.push(c)
        } else if (c in map.keys) {
            if (stack.isEmpty() || stack.pop() != map[c]) {
                return false
            }
        }
    }
    return stack.isEmpty()
}

This code correctly handles nested and sequential brackets, for example:

println(check("([]){}[(()())()]") ) // true
println(check("[(])")) // false