-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupingSymbolsChecker.java
More file actions
46 lines (38 loc) · 1.43 KB
/
GroupingSymbolsChecker.java
File metadata and controls
46 lines (38 loc) · 1.43 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
41
42
43
44
45
46
import java.util.Stack;
public class GroupingSymbolsChecker {
public static boolean isBalanced(String code) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
// Push opening symbols to stack
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
// Check closing symbols
else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty()) {
return false; // No opening symbol for this closing symbol
}
char top = stack.pop();
if (!isMatchingPair(top, ch)) {
return false;
}
}
}
// After processing, stack should be empty
return stack.isEmpty();
}
private static boolean isMatchingPair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']');
}
public static void main(String[] args) {
String code = "{ int a = (5 + 3) * [2 + 4]; }";
if (isBalanced(code)) {
System.out.println("The code has balanced grouping symbols.");
} else {
System.out.println("The code has unbalanced grouping symbols.");
}
}
}