forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0678-valid-parenthesis-string.java
54 lines (49 loc) · 1.54 KB
/
0678-valid-parenthesis-string.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
classSolution {
publicbooleancheckValidString(Strings) {
intcount = 0;
Stack<Integer> op = newStack<>();
Stack<Integer> st = newStack<>();
for (inti = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') op.push(i); // index of opening
elseif (s.charAt(i) == ')') {
if (op.size() > 0) op.pop(); // if we have brackets
elseif (st.size() > 0) st.pop(); // if not brackets do we have stars
elsereturnfalse; // a closing bracket without opening and star
} elsest.push(i); // index of star
}
// if we left with some opening bracket that over stars con cover up
while (op.size() > 0 && st.size() > 0) {
if (op.peek() > st.peek()) returnfalse;
op.pop();
st.pop();
}
returnop.size() == 0;
}
}
// Time complexity: O(n)
// Space complexity: O(1)
classSolution2 {
publicbooleancheckValidString(Strings) {
intlow = 0, high = 0;
for (inti = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
low++;
high++;
} elseif (s.charAt(i) == ')') {
if (low > 0) {
low--;
}
high--;
} else {
if (low > 0) {
low--;
}
high++;
}
if (high < 0) {
returnfalse;
}
}
returnlow == 0;
}
}