-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
63 lines (57 loc) · 1.98 KB
/
main.rs
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
fn main() {
assert_eq!(Solution::check_valid_string(String::from("()")), true);
}
struct Solution {}
impl Solution {
/// Time: O(n) two pass
/// Space: O(1)
/// just scan the array from right to left to determine each use of *
/// then scan the array from left to right to determine each use of *
pub fn check_valid_string(s: String) -> bool {
let s: Vec<char> = s.chars().collect();
let (mut w, mut r) = (0, 0);
for &c in s.iter().rev() {
match c {
'*' => w += 1,
')' => r += 1,
'(' | _ => {
if r > 0 { r -= 1 }
else if w > 0 { w -= 1 }
else { return false }
}
}
}
if r > w { return false }
let (mut w, mut l) = (0, 0);
for &c in s.iter() {
match c {
'*' => w += 1,
'(' => l += 1,
')' | _ => {
if l > 0 { l -= 1 }
else if w > 0 { w -= 1 }
else { return false }
}
}
}
l <= w
}
}
#[cfg(test)]
mod test {
use crate::*;
#[test]
fn basic() {
assert_eq!(Solution::check_valid_string(String::from("()")), true);
assert_eq!(Solution::check_valid_string(String::from("(*)")), true);
assert_eq!(Solution::check_valid_string(String::from("(*))")), true);
assert_eq!(Solution::check_valid_string(String::from("(*)))")), false);
assert_eq!(Solution::check_valid_string(String::from("(*)(()")), false);
assert_eq!(Solution::check_valid_string(String::from("(****")), true);
}
#[test]
fn fail() {
assert_eq!(Solution::check_valid_string(String::from(")))***")), false);
// assert_eq!(Solution::check_valid_string(String::from("(()(()))(()()()))))((((()*()*(())())(()))((*()(*((*(*()))()(())*()()))*)*()))()()(())()(()))())))")), false);
}
}