-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28.)balanced_bracket.java
More file actions
29 lines (24 loc) · 864 Bytes
/
Copy path28.)balanced_bracket.java
File metadata and controls
29 lines (24 loc) · 864 Bytes
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
import java.util.*;
public class BalancedBrackets {
public static boolean isBalanced(String str) {
Stack<Character> stack = new Stack<>();
for (char ch : str.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String input = "{[()]}";
System.out.println(isBalanced(input) ? "Balanced" : "Not Balanced");
}
}