-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBrackets.java
More file actions
23 lines (22 loc) · 744 Bytes
/
Copy pathBrackets.java
File metadata and controls
23 lines (22 loc) · 744 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
Determine whether a given string of parentheses (multiple types) is properly nested.
*/
import java.util.*;
class Solution {
public int solution(String S) {
Stack<Character> stack = new Stack<>();
for (char ch:S.toCharArray()) {
if (ch == '{' || ch == '(' || ch == '[') {
stack.push(ch);
} else {
if (stack.isEmpty()) return 0;
char stackTop = stack.peek();
if (ch == '}' && stackTop != '{') return 0;
if (ch == ']' && stackTop != '[') return 0;
if (ch == ')' && stackTop != '(') return 0;
stack.pop();
}
}
return stack.isEmpty() ? 1 : 0;
}
}