301. 删除无效的括号

This commit is contained in:
2026-10-10 01:01:55 +08:00
parent 582e1f1375
commit fcb9344f99
+41 -12
View File
@@ -1,28 +1,57 @@
use std::collections::HashSet;
mod arr;
mod list;
struct Solution {}
impl Solution {
pub fn remove_outer_parentheses(s: String) -> String {
pub fn remove_invalid_parentheses(s: String) -> Vec<String> {
let s = s.as_bytes().to_vec();
let mut queue1 = HashSet::new();
fn valid(x: &Vec<u8>) -> bool {
let mut cnt = 0;
let mut ans = vec![];
for c in s.chars() {
if c == '(' {
if cnt != 0 {
ans.push(c);
}
for c in x {
if *c == b'(' {
cnt += 1;
} else {
} else if *c == b')' {
cnt -= 1;
if cnt != 0 {
ans.push(c);
if cnt < 0 {
return false;
}
}
}
ans.iter().collect()
cnt == 0
}
queue1.insert(s);
loop {
{
let mut local_ans = vec![];
for x in queue1.iter() {
if valid(&x) {
local_ans.push(x.clone());
}
}
if !local_ans.is_empty() {
return local_ans
.into_iter()
.map(|x| x.iter().map(|&y| y as char).collect::<String>())
.collect();
}
}
let mut queue2 = HashSet::<Vec<u8>>::new();
for x in queue1.into_iter(){
for i in 0..x.len() {
queue2.insert( x[..i].iter().chain(x[i + 1..].iter()).copied().collect());
}
}
queue1 = queue2;
}
}
}
fn main() {
println!("{:?}", Solution::remove_outer_parentheses("(()())(())(()(()))".to_string()));
println!(
"{:?}",
Solution::remove_invalid_parentheses(")()())()))(((()()()(()".to_string())
);
}