-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0678-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
class Solution {
public boolean checkValidString(String s) {
int count = 0;
Stack<Integer> op = new Stack<>();
Stack<Integer> st = new Stack<>();
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') op.push(i); // index of opening
else if (s.charAt(i) == ')') {
if (op.size() > 0) op.pop(); // if we have brackets
else if (st.size() > 0) st.pop(); // if not brackets do we have stars
else return false; // a closing bracket without opening and star
} else st.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()) return false;
op.pop();
st.pop();
}
return op.size() == 0;
}
}
// Time complexity: O(n)
// Space complexity: O(1)
class Solution2 {
public boolean checkValidString(String s) {
int low = 0, high = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
low++;
high++;
} else if (s.charAt(i) == ')') {
if (low > 0) {
low--;
}
high--;
} else {
if (low > 0) {
low--;
}
high++;
}
if (high < 0) {
return false;
}
}
return low == 0;
}
}