1249. Minimum Remove to Make Valid Parentheses

Given a string s of '(' , ')' and lowercase English characters. 

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, contains only lowercase characters, or
  • It can be written as AB (A concatenated with B), where A and B are valid strings, or
  • It can be written as (A), where A is a valid string.

 

Example 1:

Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Example 4:

Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

 

Constraints:

  • 1 <= s.length <= 10^5
  • s[i] is one of  '(' , ')' and lowercase English letters.

Rust Solution

struct Solution;

use std::collections::HashSet;

impl Solution {
    fn min_remove_to_make_valid(s: String) -> String {
        let mut stack: Vec<usize> = vec![];
        let mut res: String = "".to_string();
        let mut remove: HashSet<usize> = HashSet::new();
        for (i, c) in s.char_indices() {
            match c {
                '(' => {
                    stack.push(i);
                }
                ')' => {
                    if stack.pop().is_none() {
                        remove.insert(i);
                    }
                }
                _ => {}
            }
        }
        for i in stack {
            remove.insert(i);
        }
        for (i, c) in s.char_indices() {
            if !remove.contains(&i) {
                res.push(c);
            }
        }
        res
    }
}

#[test]
fn test() {
    let s = "lee(t(c)o)de)".to_string();
    let res = "lee(t(c)o)de".to_string();
    assert_eq!(Solution::min_remove_to_make_valid(s), res);
    let s = "a)b(c)d".to_string();
    let res = "ab(c)d".to_string();
    assert_eq!(Solution::min_remove_to_make_valid(s), res);
    let s = "))((".to_string();
    let res = "".to_string();
    assert_eq!(Solution::min_remove_to_make_valid(s), res);
    let s = "(a(b(c)d)".to_string();
    let res = "a(b(c)d)".to_string();
    assert_eq!(Solution::min_remove_to_make_valid(s), res);
}

Having problems with this solution? Click here to submit an issue on github.