Skip to content

Commit 3514717

Browse files
authored
Create check-if-a-parentheses-string-can-be-valid.cpp
1 parent b5f9bdc commit 3514717

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
bool canBeValid(string s, string locked) {
7+
auto check = [&s, &locked](char c) {
8+
const int begin = (c == '(') ? 0 : size(s) - 1;
9+
const int end = (c == '(') ? size(s) : -1;
10+
const int d = (c == '(') ? 1 : -1;
11+
for (int i = begin, cnt = 0, bal = 0; i != end; i += d) {
12+
if (locked[i] == '0') {
13+
++cnt;
14+
} else {
15+
bal += (s[i] == c) ? 1 : -1;
16+
if (cnt + bal < 0) {
17+
return false;
18+
}
19+
}
20+
}
21+
return true;
22+
};
23+
24+
return size(s) % 2 == 0 && check('(') && check(')');
25+
}
26+
};

0 commit comments

Comments
 (0)