-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12_jan
99 lines (81 loc) · 2.7 KB
/
12_jan
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/\*
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:
It is ().
It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.
It can be written as (A), where A is a valid parentheses string.
You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked,
If locked[i] is '1', you cannot change s[i].
But if locked[i] is '0', you can change s[i] to either '(' or ')'.
Return true if you can make s a valid parentheses string. Otherwise, return false.
Example 1:
Input: s = "))()))", locked = "010100"
Output: true
Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].
We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.
\*/
//approch 1
class Solution {
public:
bool canBeValid(string s, string locked) {
int n = s.length();
if (n % 2 != 0)
return false;
stack<int> open;
stack<int> openClose;
for (int i = 0; i < n; i++) {
if (locked[i] == '0') {
openClose.push(i);
} else if (s[i] == '(') {
open.push(i);
} else if (s[i] == ')') {
if (!open.empty()) {
open.pop();
} else if (!openClose.empty()) {
openClose.pop();
} else {
return false;
}
}
}
while (!open.empty() && !openClose.empty() && open.top() < openClose.top()) {
open.pop();
openClose.pop();
}
return open.empty();
}
};
//approch 2
class Solution {
public:
bool canBeValid(string s, string locked) {
int n = s.length();
if (n % 2 != 0) {
return false; // Odd length cannot form valid parentheses
}
// Left-to-right pass: Ensure there are enough open brackets
int openCount = 0;
for (int i = 0; i < n; i++) {
if (s[i] == '(' || locked[i] == '0') {
openCount++;
} else { // s[i] == ')' and locked[i] == '1'
openCount--;
}
if (openCount < 0) {
return false; // Too many ')' encountered
}
}
// Right-to-left pass: Ensure there are enough close brackets
int closeCount = 0;
for (int i = n - 1; i >= 0; i--) {
if (s[i] == ')' || locked[i] == '0') {
closeCount++;
} else { // s[i] == '(' and locked[i] == '1'
closeCount--;
}
if (closeCount < 0) {
return false; // Too many '(' encountered
}
}
return true;
}
};