Learn how to check balanced parentheses in Java using Stack.
Balanced Parentheses in Java is a common programming interview problem that checks whether opening and closing brackets are correctly matched. Using a Stack data structure, we can efficiently verify balanced parentheses containing characters such as (), {}, and [].
Code Explanation (Step-by-Step)
- Create a string containing brackets.
- Create a Stack<Character> object.
- Traverse the string using a for loop.
- Extract each character using str.charAt() method.
- Push opening brackets (, {, [ onto the stack.
- When a closing bracket is found, check whether it matches the top element of the stack.
- If matched, remove the opening bracket using pop().
- After traversing the complete string, check whether the stack is empty.
- If the stack is empty, the brackets are balanced.
- Otherwise, the brackets are not balanced.
import java.util.Stack;
public class BalancedParanthsisMain {
public static void main(String[] args) {
String str = "{[()]}";
Stack st = new Stack();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (st.empty()) {
st.push(str.charAt(i));
} else if (ch == '{' || ch == '[' || ch == '(') {
st.push(ch);
} else if (ch == '}' && st.peek() == '{') {
st.pop();
} else if (ch == ']' && st.peek() == '[') {
st.pop();
} else if (ch == ')' && st.peek() == '(') {
st.pop();
}
}
if (st.empty()) {
System.out.println("Given input String " + str + " is well formed");
} else {
System.out.println("Given input String " + str + " not well formed");
}
}
}
Output :- Given input String {[()]} is well formed
Java Program to Check Balanced Parentheses Using contains
public class BalancedParenthesesMain {
public static void main(String[] args) {
String str = "{[()]}";
while (str.contains("()") || str.contains("{}") || str.contains("[]")) {
str = str.replace("()", "");
str = str.replace("{}", "");
str = str.replace("[]", "");
}
if (str.isEmpty()) {
System.out.println("Given input String is well formed");
} else {
System.out.println("Given input String is not well formed");
}
}
}
Here are some Java-related programs that will help you understand Java concepts better:
FAQ
What are balanced parentheses in Java?
Balanced parentheses mean that every opening bracket has a corresponding closing bracket in the correct order.
Which data structure is used to check balanced parentheses?
A Stack is commonly used because it follows the LIFO (Last In First Out) principle.
What is the time complexity of the balanced parentheses algorithm?
The time complexity is O(n), where n is the length of the input string.
Why is Stack suitable for parentheses matching?
Stack stores opening brackets and removes them when matching closing brackets appear, making validation efficient.
Can this program handle all bracket types?
Yes, it can validate parentheses (), square brackets [], and curly braces {}.