1111. 有效括号的嵌套深度

This commit is contained in:
2026-09-30 16:38:03 +08:00
parent a2f7ac206a
commit 854d77f03f
+25 -48
View File
@@ -1,66 +1,43 @@
use crate::arr::make_char_matrix;
use std::collections::HashSet;
mod arr; mod arr;
mod list; mod list;
struct Solution {} struct Solution {}
impl Solution { impl Solution {
pub fn has_valid_path(grid: Vec<Vec<char>>) -> bool { pub fn max_depth_after_split(seq: String) -> Vec<i32> {
if grid[0][0] == ')' let seq = seq.as_bytes();
|| grid[grid.len() - 1][grid[0].len() - 1] == '(' let mut depth = 0;
|| (grid.len() + grid[0].len()) % 2 == 0 let mut max_depth = 0;
{ for c in seq {
return false; if *c == '(' as u8 {
depth += 1;
max_depth = max_depth.max(depth);
} else {
depth -= 1;
}
} }
let mut matrix = vec![vec![Option::<HashSet<i32>>::None; grid[0].len()]; grid.len()]; let target_depth = max_depth / 2;
matrix[0][0] = Some(HashSet::from_iter([10000])); let mut ans = vec![0; seq.len()];
for i in 0..=(grid.len() - 1 + grid[0].len() - 1) { for i in 0..seq.len() {
for j in 0..=i { if seq[i] == '(' as u8 {
if grid.len() > j && grid[0].len() > i - j { depth += 1;
if grid.len() > j + 1 { if depth > target_depth {
let (rsrc, rdst) = matrix.split_at_mut(j + 1); ans[i] = 1;
let dst = rdst[0][i - j].get_or_insert_with(HashSet::new); }
let src = rsrc[j][i - j].as_ref().unwrap(); } else {
if grid[j + 1][i - j] == '(' { depth -= 1;
dst.extend(src.iter().map(|&x| x + 10000)); if depth + 1 > target_depth {
} else { ans[i] = 1;
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),
);
}
}
} }
} }
} }
matrix[grid.len() - 1][grid[0].len() - 1].as_ref() ans
.unwrap()
.iter()
.any(|&x| x / 10000 == x % 10000)
} }
} }
fn main() { fn main() {
println!( println!(
"{:?}", "{:?}",
Solution::has_valid_path(make_char_matrix( Solution::max_depth_after_split("()(())()".to_string())
r#"[["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]"#
))
); );
} }