Middle+
/** * Checks whether brackets are balanced in a string. * Brackets that may appear in the string: * [[{ and }]] * @param {string} str * @return {boolean} */ function parentheses(str) { const open = ['(', '[', '{']; const close = [')', ']', '}']; const stack = []; for (let i = 0; i < str.length; i++) { const letter = str[i]; if (open.includes(letter)) { stack.push(letter); } else if (close.includes(letter)) { const index = close.indexOf(letter); const lastOpenIndex = stack.length - 1; if (open[index] !== stack[lastOpenIndex]) { return false; } else { stack.splice(lastOpenIndex, 1); } } } return stack.length === 0; }
sobes.tech AI
Answer from AI
The function checks whether brackets are balanced in a string using a stack.
Idea:
- When an opening bracket is encountered, push it onto the stack.
- When a closing bracket is encountered, check if it matches the last opened bracket (top of the stack).
- If it doesn't match, return false.
- At the end, if the stack is empty, all brackets are correctly closed.
Example usage:
console.log(parentheses("{[()()]}") ); // true
console.log(parentheses("{[(])}") ); // false
The function correctly handles round, square, and curly brackets.