Stacks: Last-In, First-Out (LIFO)
Queues: First-In, First-Out (FIFO)
Problem: Write a program that checks if parentheses, brackets, and braces are properly balanced in a string.
Examples:
public class BalancedParentheses {
// Test cases
public static void main(String[] args) {
String[] testCases = {
"()", // true
"()[]{}", // true
"()[]{}", // true
"([{}])", // true
"([{}])", // true
"(]", // false
"([)]", // false
"(((", // false
"", // true (empty string is balanced)
"({[]})", // true
"((())", // false
"hello(world)", // true (ignores non-bracket chars)
")(", // false
"[(])" // false
};
System.out.println("Testing Balanced Parentheses Checker:\n");
for (String test : testCases) {
boolean result = isBalanced(test);
System.out.printf("'%s' -> %s%n", test, result);
}
}
public static boolean isBalanced(String test) {
// to implement
}
private static boolean isOpenParentheses(char c) {
return c == '(' || c == '[' || c == '{';
}
private static boolean isCloseParentheses(char c) {
return c == ')' || c == ']' || c == '}';
}
private static boolean isAMatch(char open, char close) {
return (int) (close - open) < 3 && (int) (close - open) > 0;
}
}