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
(s: String)
| 10 | /// just scan the array from right to left to determine each use of * |
| 11 | /// then scan the array from left to right to determine each use of * |
| 12 | pub fn check_valid_string(s: String) -> bool { |
| 13 | let s: Vec<char> = s.chars().collect(); |
| 14 | let (mut w, mut r) = (0, 0); |
| 15 | for &c in s.iter().rev() { |
| 16 | match c { |
| 17 | '*' => w += 1, |
| 18 | ')' => r += 1, |
| 19 | '(' | _ => { |
| 20 | if r > 0 { r -= 1 } |
| 21 | else if w > 0 { w -= 1 } |
| 22 | else { return false } |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | if r > w { return false } |
| 27 | let (mut w, mut l) = (0, 0); |
| 28 | for &c in s.iter() { |
| 29 | match c { |
| 30 | '*' => w += 1, |
| 31 | '(' => l += 1, |
| 32 | ')' | _ => { |
| 33 | if l > 0 { l -= 1 } |
| 34 | else if w > 0 { w -= 1 } |
| 35 | else { return false } |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | l <= w |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[cfg(test)] |