LeetCode 1249. Minimum Remove to Make Valid Parentheses

Problem Statement



use std::collections::HashSet;

impl Solution {
pub fn min_remove_to_make_valid(s: String) -> String {
let mut stack = vec![];
let mut remove = vec![];
for i in 0..s.len() {
let c = s.chars().nth(i).unwrap();
if c == '(' {
stack.push(i);
} else if c == ')' {
if !stack.is_empty() {
stack.pop();
} else {
remove.push(i);
}
}
}

while !stack.is_empty() {
remove.push(stack.last().unwrap().clone());
stack.pop();
}

let mut ans = "".to_string();
let set : HashSet<usize> = remove.into_iter().collect();
for i in 0..s.len() {
if !set.contains(&i) {
ans.push(s.chars().nth(i).unwrap());
}
}
return ans;
}
}