-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCheckRedundantBrackets.java
More file actions
50 lines (42 loc) · 1.45 KB
/
CheckRedundantBrackets.java
File metadata and controls
50 lines (42 loc) · 1.45 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
package stacks.Assignment;
import java.util.Stack;
/*Given a single string mathematical expression, return true if
redundant brackets are present in the expression. Brackets are redundant if
there is nothing inside the bracket or more than one pair of brackets are present.
Assume the given string expression is balanced and contains only one type of
bracket i.e. ().
Sample Input:
((a+b))
(a+b)
Sample Output:
true
false*/
public class CheckRedundantBrackets {
private static boolean find(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
public static boolean checkRedundant(String expression) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < expression.length(); i++) {
if (expression.charAt(i) == '(' || find(expression.charAt(i))) {
stack.push(expression.charAt(i));
} else if (expression.charAt(i) == ')') {
boolean hasOperator = false;
while (!stack.isEmpty() && stack.peek() != '(') {
stack.pop();
hasOperator = true;
}
if (!hasOperator) {
return true;
}
if (!stack.isEmpty()) {
stack.pop();
}
}
}
return false;
}
public static void main(String[] args) {
System.out.println(checkRedundant("((a+b))"));
}
}