|
| 1 | +// 921. Minimum Add to Make Parentheses Valid |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/ |
| 5 | +// |
| 6 | +// Tags: String - Stack - Greedy |
| 7 | + |
| 8 | +struct Solution; |
| 9 | +impl Solution { |
| 10 | + /// Iterate over the input keeping track of the number of open left parentheses we find, for |
| 11 | + /// each unmatched or extra parentheses we will need to add a matching one. |
| 12 | + /// |
| 13 | + /// Time complexity: O(n) |
| 14 | + /// Space complexity: O(1) |
| 15 | + /// |
| 16 | + /// Runtime 1 ms Beats 58% |
| 17 | + /// Memory 2.18 MB Beats 23% |
| 18 | + pub fn min_add_to_make_valid(s: String) -> i32 { |
| 19 | + let (mut left, mut right) = (0, 0); |
| 20 | + for c in s.chars() { |
| 21 | + if c == '(' { |
| 22 | + right += 1; |
| 23 | + } else if right > 0 { |
| 24 | + right -= 1; |
| 25 | + } else { |
| 26 | + left += 1; |
| 27 | + } |
| 28 | + } |
| 29 | + right + left |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Tests. |
| 34 | +fn main() { |
| 35 | + let tests = [("())", 1), ("(((", 3)]; |
| 36 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 37 | + let mut success = 0; |
| 38 | + for (i, t) in tests.iter().enumerate() { |
| 39 | + let res = Solution::min_add_to_make_valid(t.0.to_string()); |
| 40 | + if res == t.1 { |
| 41 | + success += 1; |
| 42 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 43 | + } else { |
| 44 | + println!( |
| 45 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 46 | + i, t.1, res |
| 47 | + ); |
| 48 | + } |
| 49 | + } |
| 50 | + println!(); |
| 51 | + if success == tests.len() { |
| 52 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 53 | + } else if success == 0 { |
| 54 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 55 | + } else { |
| 56 | + println!( |
| 57 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 58 | + tests.len() - success |
| 59 | + ) |
| 60 | + } |
| 61 | +} |
0 commit comments