-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJan12 2025 DC.java
38 lines (36 loc) · 1.27 KB
/
Jan12 2025 DC.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
2116. Check if a Parentheses String Can Be Valid
import java.util.Stack;
class Solution {
public boolean canBeValid(String s, String locked) {
int stringLength = s.length();
if (stringLength % 2 == 1) {
return false;
}
Stack<Integer> openIndices = new Stack<>();
Stack<Integer> unlockedIndices = new Stack<>();
for (int i = 0; i < stringLength; i++) {
if (locked.charAt(i) == '0') {
unlockedIndices.push(i);
} else if (s.charAt(i) == '(') {
openIndices.push(i);
} else if (s.charAt(i) == ')') {
if (!openIndices.isEmpty()) {
openIndices.pop();
} else if (!unlockedIndices.isEmpty()) {
unlockedIndices.pop();
} else {
return false;
}
}
}
while (!openIndices.isEmpty() && !unlockedIndices.isEmpty() &&
openIndices.peek() < unlockedIndices.peek()) {
openIndices.pop();
unlockedIndices.pop();
}
if (openIndices.isEmpty() && !unlockedIndices.isEmpty()) {
return unlockedIndices.size() % 2 == 0;
}
return openIndices.isEmpty();
}
}