-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBrackets.java
More file actions
33 lines (29 loc) Β· 860 Bytes
/
Copy pathBrackets.java
File metadata and controls
33 lines (29 loc) Β· 860 Bytes
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
import java.util.Stack;
public class Brackets {
public int solution(String S) {
Stack<Character> stack = new Stack<>();
for (Character c : S.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return 0;
}
Character peek = stack.peek();
if (c == ')' && peek == '(') {
stack.pop();
} else if (c == ']' && peek == '[') {
stack.pop();
} else if (c == '}' && peek == '{') {
stack.pop();
} else {
return 0;
}
}
}
if (stack.isEmpty()) {
return 1;
}
return 0;
}
}