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