Skip to content

Commit 9d40369

Browse files
authored
Create Check if a Parentheses String Can Be Valid.java
1 parent c8ba835 commit 9d40369

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public boolean canBeValid(String s, String locked) {
3+
if (s.length() % 2 != 0) {
4+
return false;
5+
}
6+
Stack<Integer> openBrackets = new Stack<>();
7+
Stack<Integer> unlocked = new Stack<>();
8+
for (int i = 0; i < s.length(); i++) {
9+
char c = s.charAt(i);
10+
if (locked.charAt(i) == '0') {
11+
unlocked.push(i);
12+
} else if (c == '(') {
13+
openBrackets.push(i);
14+
} else if (c == ')') {
15+
if (!openBrackets.isEmpty()) {
16+
openBrackets.pop();
17+
} else if (!unlocked.isEmpty()) {
18+
unlocked.pop();
19+
} else {
20+
return false;
21+
}
22+
}
23+
}
24+
while (!openBrackets.isEmpty() && !unlocked.isEmpty() && openBrackets.peek() < unlocked.peek()) {
25+
openBrackets.pop();
26+
unlocked.pop();
27+
}
28+
return openBrackets.isEmpty();
29+
}
30+
}

0 commit comments

Comments
 (0)