-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBalancedParentheses.java
More file actions
36 lines (31 loc) · 1.29 KB
/
BalancedParentheses.java
File metadata and controls
36 lines (31 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Stack;
public class BalancedParentheses {
public static boolean isBalanced(String input) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
if (currentChar == '(' || currentChar == '[' || currentChar == '{') {
stack.push(currentChar);
} else if (currentChar == ')' || currentChar == ']' || currentChar == '}') {
if (stack.isEmpty()) {
return false; // Unmatched closing parenthesis
}
char top = stack.pop();
if (currentChar == ')' && top != '(' || currentChar == ']' && top != '['
|| currentChar == '}' && top != '{') {
return false; // Mismatched parentheses
}
}
}
return stack.isEmpty(); // Stack should be empty for balanced parentheses
}
public static void main(String[] args) {
String input = "{[()]}";
boolean result = isBalanced(input);
if (result) {
System.out.println("The input contains balanced parentheses.");
} else {
System.out.println("The input does not contain balanced parentheses.");
}
}
}