Compare commits

...
4 Commits
Author SHA1 Message Date
li_chx fcb9344f99 301. 删除无效的括号 2026-10-10 01:01:55 +08:00
li_chx 582e1f1375 1021. 删除最外层的括号 2026-10-09 16:09:42 +08:00
li_chx 9f268359d2 1541. 平衡括号字符串的最少插入次数 2026-10-09 16:04:46 +08:00
li_chx 854d77f03f 1111. 有效括号的嵌套深度 2026-09-30 16:38:03 +08:00
+38 -47
View File
@@ -1,4 +1,3 @@
use crate::arr::make_char_matrix;
use std::collections::HashSet;
mod arr;
@@ -6,61 +5,53 @@ mod list;
struct Solution {}
impl Solution {
pub fn has_valid_path(grid: Vec<Vec<char>>) -> bool {
if grid[0][0] == ')'
|| grid[grid.len() - 1][grid[0].len() - 1] == '('
|| (grid.len() + grid[0].len()) % 2 == 0
{
return false;
}
let mut matrix = vec![vec![Option::<HashSet<i32>>::None; grid[0].len()]; grid.len()];
matrix[0][0] = Some(HashSet::from_iter([10000]));
for i in 0..=(grid.len() - 1 + grid[0].len() - 1) {
for j in 0..=i {
if grid.len() > j && grid[0].len() > i - j {
if grid.len() > j + 1 {
let (rsrc, rdst) = matrix.split_at_mut(j + 1);
let dst = rdst[0][i - j].get_or_insert_with(HashSet::new);
let src = rsrc[j][i - j].as_ref().unwrap();
if grid[j + 1][i - j] == '(' {
dst.extend(src.iter().map(|&x| x + 10000));
} else {
dst.extend(
src.iter()
.filter(|&x| x / 10000 > x % 10000)
.map(|&x| x + 1),
);
}
}
if grid[0].len() > i - j + 1 {
let (rsrc, rdst) = matrix[j].split_at_mut(i - j + 1);
let dst = rdst[0].get_or_insert_with(HashSet::new);
let src = rsrc[i - j].as_ref().unwrap();
if grid[j][i - j + 1] == '(' {
dst.extend(src.iter().map(|&x| x + 10000));
} else {
dst.extend(
src.iter()
.filter(|&x| x / 10000 > x % 10000)
.map(|&x| x + 1),
);
}
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;
}
matrix[grid.len() - 1][grid[0].len() - 1].as_ref()
.unwrap()
.iter()
.any(|&x| x / 10000 == x % 10000)
}
}
fn main() {
println!(
"{:?}",
Solution::has_valid_path(make_char_matrix(
r#"[["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]"#
))
Solution::remove_invalid_parentheses(")()())()))(((()()()(()".to_string())
);
}