-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_16.java
More file actions
65 lines (56 loc) · 2.07 KB
/
Problem_16.java
File metadata and controls
65 lines (56 loc) · 2.07 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package strings;
// Blanaced
import java.util.Stack;
public class Problem_16 {
public static boolean isBalanced(String expression) {
if (expression == null || expression.isEmpty()) {
return true; // Empty string is considered balanced
}
Stack<Character> openingBrackets = new Stack<>();
char[] chars = expression.toCharArray();
for (char c : chars) {
switch (c) {
case '{':
case '(':
case '[':
openingBrackets.push(c); // Push opening brackets to the stack
break;
case '}':
if (openingBrackets.isEmpty() || openingBrackets.pop() != '{') {
return false; // Mismatched closing bracket
}
break;
case ')':
if (openingBrackets.isEmpty() || openingBrackets.pop() != '(') {
return false; // Mismatched closing bracket
}
break;
case ']':
if (openingBrackets.isEmpty() || openingBrackets.pop() != '[') {
return false; // Mismatched closing bracket
}
break;
default:
// Ignore non-bracket characters
break;
}
}
// After iterating through all characters, check if any opening brackets remain
// unclosed
return openingBrackets.isEmpty();
}
public static void main(String[] args) {
String expression1 = "{([])}";
String expression2 = "[(])";
if (isBalanced(expression1)) {
System.out.println(expression1 + " is balanced.");
} else {
System.out.println(expression1 + " is not balanced.");
}
if (isBalanced(expression2)) {
System.out.println(expression2 + " is balanced.");
} else {
System.out.println(expression2 + " is not balanced.");
}
}
}