301. 删除无效的括号
This commit is contained in:
+44
-15
@@ -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<String> {
|
||||
let s = s.as_bytes().to_vec();
|
||||
let mut queue1 = HashSet::new();
|
||||
fn valid(x: &Vec<u8>) -> 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::<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() {
|
||||
println!("{:?}", Solution::remove_outer_parentheses("(()())(())(()(()))".to_string()));
|
||||
println!(
|
||||
"{:?}",
|
||||
Solution::remove_invalid_parentheses(")()())()))(((()()()(()".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user