-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckValidString
More file actions
34 lines (29 loc) · 905 Bytes
/
checkValidString
File metadata and controls
34 lines (29 loc) · 905 Bytes
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
class Solution {
public boolean checkValidString(String s) {
int minOpen = 0;
int maxOpen = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
minOpen++;
maxOpen++;
} else if (c == ')') {
minOpen--;
maxOpen--;
} else { // Wildcard '*'
minOpen--; // Treated as ')'
maxOpen++; // Treated as '('
}
// Too many closing parentheses
if (maxOpen < 0) {
return false;
}
// minOpen cannot be negative
if (minOpen < 0) {
minOpen = 0;
}
}
// Valid if all open parentheses can be closed
return minOpen == 0;
}
}