-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatchParentheses.java
More file actions
35 lines (29 loc) · 1.03 KB
/
MatchParentheses.java
File metadata and controls
35 lines (29 loc) · 1.03 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
import java.util.Stack;
public class MatchParentheses {
public static void main(String[] args) {
String expression = "{[(2+3)*(5-1)]}";
boolean result = isBalanced(expression);
System.out.println("Expression: " + expression);
System.out.println("Balanced: " + result);
}
public static boolean isBalanced(String expr) {
Stack<Character> stack = new Stack<>();
for (char ch : expr.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();
}
}
Output:
Expression: {[(2+3)*(5-1)]}
Balanced: true