From fcb9344f99bc18b0f210bee595fd756e7a3626ef Mon Sep 17 00:00:00 2001 From: li-chx Date: Sat, 10 Oct 2026 01:01:55 +0800 Subject: [PATCH] =?UTF-8?q?301.=20=E5=88=A0=E9=99=A4=E6=97=A0=E6=95=88?= =?UTF-8?q?=E7=9A=84=E6=8B=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 59 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 294b626..4cbbdad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,28 +1,57 @@ +use std::collections::HashSet; + mod arr; mod list; struct Solution {} impl Solution { - pub fn remove_outer_parentheses(s: String) -> String { - let mut cnt = 0; - let mut ans = vec![]; - for c in s.chars() { - if c == '(' { - if cnt != 0 { - ans.push(c); - } - cnt += 1; - } else { - cnt -= 1; - if cnt != 0 { - ans.push(c); + pub fn remove_invalid_parentheses(s: String) -> Vec { + let s = s.as_bytes().to_vec(); + let mut queue1 = HashSet::new(); + fn valid(x: &Vec) -> bool { + let mut cnt = 0; + for c in x { + if *c == b'(' { + cnt += 1; + } else if *c == b')' { + cnt -= 1; + if cnt < 0 { + return false; + } } } + 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::()) + .collect(); + } + } + let mut queue2 = HashSet::>::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; } - ans.iter().collect() } } fn main() { - println!("{:?}", Solution::remove_outer_parentheses("(()())(())(()(()))".to_string())); + println!( + "{:?}", + Solution::remove_invalid_parentheses(")()())()))(((()()()(()".to_string()) + ); }