jason89521 / leetcode_note

0 stars 0 forks source link

1249. Minimum Remove to Make Valid Parentheses #8

Open jason89521 opened 3 months ago

jason89521 commented 3 months ago

Practice Dates

Description

Link: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/description/

Solution

impl Solution {
    pub fn min_remove_to_make_valid(s: String) -> String {
        let mut left_stack = vec![];
        let mut remove_set = std::collections::HashSet::new();
        for (idx, ch) in s.chars().enumerate() {
            if ch == '(' {
                left_stack.push(idx);
            } else if ch == ')' {
                if let Some(left) = left_stack.last() {
                    left_stack.pop();
                } else {
                    remove_set.insert(idx);
                }
            } else {
            }
        }

        for &idx in left_stack.iter() {
            remove_set.insert(idx);
        }

        s.chars().enumerate().fold(String::from(""), |mut acc, (idx, ch)| {
            if !remove_set.contains(&idx) {
                acc.push(ch);
            } 
            acc
        })
    }
}

Performance

Time complexity: