forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDuplicateBrackets.java
More file actions
55 lines (50 loc) · 1.66 KB
/
DuplicateBrackets.java
File metadata and controls
55 lines (50 loc) · 1.66 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
package com.thealgorithms.stacks;
import java.util.Stack;
/**
* Class for detecting unnecessary or redundant brackets in a mathematical
* expression.
* Assumes the expression is balanced (i.e., all opening brackets have matching
* closing brackets).
*/
public final class DuplicateBrackets {
private DuplicateBrackets() {
}
/**
* Checks for extra or redundant brackets in a given expression.
*
* @param expression the string representing the expression to be checked
* @return true if there are extra or redundant brackets, false otherwise
* @throws IllegalArgumentException if the input string is null
*/
public static boolean check(String expression) {
if (expression == null) {
throw new IllegalArgumentException("Input expression cannot be null.");
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (ch == ')') {
if (stack.isEmpty() || stack.peek() == '(') {
return true;
}
while (!stack.isEmpty() && stack.peek() != '(') {
stack.pop();
}
if (!stack.isEmpty()) {
stack.pop();
}
} else {
stack.push(ch);
}
}
return false;
}
}
/**
* Time Complexity: O(n)
* reason - Iterates through the expression once; each character is processed
* constant times.
* Space Complexity: O(n)
* reason - Stack stores characters, growing linearly with expression length in
* worst case.
*/