Junior — Middle
How to implement a check for correct parentheses placement in a string using the Valid Parentheses problem on LeetCode?
sobes.tech AI
Answer from AI
To check the correctness of bracket placement in a string, a stack can be used. The idea is to iterate through the characters of the string and:
- If the character is an opening bracket (for example, '(', '{', '['), push it onto the stack.
- If the character is a closing bracket, check that the top element of the stack is the corresponding opening bracket. If yes, pop it from the stack; otherwise, the string is incorrect.
At the end, if the stack is empty, all brackets are correctly closed.
Example in Java/Kotlin:
fun isValid(s: String): Boolean {
val stack = mutableListOf<Char>()
val pairs = mapOf(')' to '(', ']' to '[', '}' to '{')
for (char in s) {
if (char in pairs.values) {
stack.add(char)
} else if (char in pairs.keys) {
if (stack.isEmpty() || stack.removeAt(stack.size - 1) != pairs[char]) {
return false
}
}
}
return stack.isEmpty()
}
This method efficiently checks the correctness of nesting and matching brackets.