1541. 平衡括号字符串的最少插入次数
This commit is contained in:
+28
-29
@@ -1,43 +1,42 @@
|
|||||||
|
|
||||||
mod arr;
|
mod arr;
|
||||||
mod list;
|
mod list;
|
||||||
|
|
||||||
struct Solution {}
|
struct Solution {}
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn max_depth_after_split(seq: String) -> Vec<i32> {
|
pub fn min_insertions(s: String) -> i32 {
|
||||||
let seq = seq.as_bytes();
|
let s = s.as_bytes();
|
||||||
let mut depth = 0;
|
let mut emp_s = vec![];
|
||||||
let mut max_depth = 0;
|
let mut ans = 0;
|
||||||
for c in seq {
|
let mut i = 0;
|
||||||
if *c == '(' as u8 {
|
while i < s.len() {
|
||||||
depth += 1;
|
if s[i] == b'(' {
|
||||||
max_depth = max_depth.max(depth);
|
emp_s.push(b'(');
|
||||||
} else {
|
} else {
|
||||||
depth -= 1;
|
if i + 1 >= s.len() || s[i + 1] != b')' {
|
||||||
}
|
ans += 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 {
|
} else {
|
||||||
depth -= 1;
|
i += 1;
|
||||||
if depth + 1 > target_depth {
|
}
|
||||||
ans[i] = 1;
|
emp_s.push(b')');
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
let mut cnt = 0;
|
||||||
|
for (i, c) in emp_s.iter().enumerate() {
|
||||||
|
if *c == b'(' {
|
||||||
|
if cnt < 0 {
|
||||||
|
ans += -cnt;
|
||||||
|
cnt = 0;
|
||||||
|
}
|
||||||
|
cnt += 1;
|
||||||
|
} else {
|
||||||
|
cnt -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
if cnt < 0 { ans - cnt } else { ans + cnt * 2 }
|
||||||
ans
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!(
|
println!("{:?}", Solution::min_insertions("()()))((".to_string()));
|
||||||
"{:?}",
|
|
||||||
Solution::max_depth_after_split("()(())()".to_string())
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user