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 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;
pub fn max_depth_after_split(seq: String) -> Vec<i32> {
let seq = seq.as_bytes();
let mut depth = 0;
let mut max_depth = 0;
for c in seq {
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()];
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),
);
}
}
let target_depth = max_depth / 2;
let mut ans = vec![0; seq.len()];
for i in 0..seq.len() {
if seq[i] == '(' as u8 {
depth += 1;
if depth > target_depth {
ans[i] = 1;
}
} else {
depth -= 1;
if depth + 1 > target_depth {
ans[i] = 1;
}
}
}
matrix[grid.len() - 1][grid[0].len() - 1].as_ref()
.unwrap()
.iter()
.any(|&x| x / 10000 == x % 10000)
ans
}
}
fn main() {
println!(
"{:?}",
Solution::has_valid_path(make_char_matrix(
r#"[["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]"#
))
Solution::max_depth_after_split("()(())()".to_string())
);
}