Java stacks and balanced brackets
A stack is a last-in, first-out structure: the item pushed most recently is the first one popped. In Java, ArrayDeque is the recommended implementation, with push, pop, and peek working at the top. The older Stack class is synchronized and not recommended for new code.
Java
import java.util.*;
class Main {
static boolean balanced(String text) {
Deque<Character> stack = new ArrayDeque<>();
for (char ch : text.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else if (ch == ')' || ch == ']' || ch == '}') {
if (stack.isEmpty()) {
return false;
}
char open = stack.pop();
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String[] tests = {"(a[b]{c})", "(]", "((", ")(", ""};
for (String test : tests) {
System.out.println("'" + test + "' -> " + balanced(test));
}
}
}