forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDuplicateBrackets.java
38 lines (34 loc) · 1.12 KB
/
DuplicateBrackets.java
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
package com.thealgorithms.stacks;
// 1. You are given a string exp representing an expression.
// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each
// other.
// 3. But, some of the pair of brackets maybe extra/needless.
// 4. You are required to print true if you detect extra brackets and false otherwise.
// e.g.'
// ((a + b) + (c + d)) -> false
// (a + b) + ((c + d)) -> true
import java.util.Stack;
public final class DuplicateBrackets {
private DuplicateBrackets() {
}
public static boolean check(String str) {
Stack<Character> st = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == ')') {
if (st.peek() == '(') {
return true;
} else {
while (st.size() > 0 && st.peek() != '(') {
st.pop();
}
st.pop();
}
} else {
st.push(ch);
}
// System.out.println(st);
}
return false;
}
}