We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static String isBalanced(String s) {
// Use ArrayDeque instead of Stack for better performance
Deque<Character> stack = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
// Push opening brackets onto the stack
switch (ch) {
case '(':
case '[':
case '{':
stack.push(ch);
break;
default:
// If the stack is empty or brackets don't match, return "NO"
if (stack.isEmpty() //
|| !isMatchingPair(stack.pop(), ch)) {
return "NO";
}
break;
}
}
// If the stack is empty, the string is balanced
return stack.isEmpty() ? "YES" : "NO";
}
// Helper method to check if brackets match
private static boolean isMatchingPair(char open, char close) {
return (open == '(' && close == ')') //
|| (open == '[' && close == ']') //
|| (open == '{' && close == '}');
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Balanced Brackets
You are viewing a single comment's thread. Return to all comments →