301. 删除无效的括号
This commit is contained in:
+44
-15
@@ -1,28 +1,57 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
mod arr;
|
mod arr;
|
||||||
mod list;
|
mod list;
|
||||||
|
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn remove_outer_parentheses(s: String) -> String {
|
pub fn remove_invalid_parentheses(s: String) -> Vec<String> {
|
||||||
let mut cnt = 0;
|
let s = s.as_bytes().to_vec();
|
||||||
let mut ans = vec![];
|
let mut queue1 = HashSet::new();
|
||||||
for c in s.chars() {
|
fn valid(x: &Vec<u8>) -> bool {
|
||||||
if c == '(' {
|
let mut cnt = 0;
|
||||||
if cnt != 0 {
|
for c in x {
|
||||||
ans.push(c);
|
if *c == b'(' {
|
||||||
}
|
cnt += 1;
|
||||||
cnt += 1;
|
} else if *c == b')' {
|
||||||
} else {
|
cnt -= 1;
|
||||||
cnt -= 1;
|
if cnt < 0 {
|
||||||
if cnt != 0 {
|
return false;
|
||||||
ans.push(c);
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
ans.iter().collect()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("{:?}", Solution::remove_outer_parentheses("(()())(())(()(()))".to_string()));
|
println!(
|
||||||
|
"{:?}",
|
||||||
|
Solution::remove_invalid_parentheses(")()())()))(((()()()(()".to_string())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user