-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedBrackets.java
More file actions
40 lines (35 loc) · 1.23 KB
/
BalancedBrackets.java
File metadata and controls
40 lines (35 loc) · 1.23 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
37
38
39
40
// Balanced Brackets Checker
import java.util.Scanner;
import java.util.Stack;
public class BalancedBrackets {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the bracket expression:");
String expression = sc.nextLine();
if (isBalanced(expression)) {
System.out.println("Balanced");
} else {
System.out.println("Not Balanced");
}
sc.close();
}
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 (!isMatching(top, ch)) return false;
}
}
return stack.isEmpty();
}
public static boolean isMatching(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']');
}
}