From 582e1f1375305e97079588a1d70ad34e7fc95e3b Mon Sep 17 00:00:00 2001 From: li-chx Date: Fri, 9 Oct 2026 16:09:42 +0800 Subject: [PATCH] =?UTF-8?q?1021.=20=E5=88=A0=E9=99=A4=E6=9C=80=E5=A4=96?= =?UTF-8?q?=E5=B1=82=E7=9A=84=E6=8B=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main.rs | 36 +++++++++++------------------------- 1 file changed, 11 insertions(+), 25 deletions(-) diff --git a/src/main.rs b/src/main.rs index 06fab3e..294b626 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,40 +3,26 @@ mod list; struct Solution {} impl Solution { - 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 { - if i + 1 >= s.len() || s[i + 1] != b')' { - ans += 1; - } else { - i += 1; - } - emp_s.push(b')'); - } - i += 1; - } + pub fn remove_outer_parentheses(s: String) -> String { let mut cnt = 0; - for (i, c) in emp_s.iter().enumerate() { - if *c == b'(' { - if cnt < 0 { - ans += -cnt; - cnt = 0; + let mut ans = vec![]; + for c in s.chars() { + if c == '(' { + if cnt != 0 { + ans.push(c); } cnt += 1; } else { cnt -= 1; + if cnt != 0 { + ans.push(c); + } } } - if cnt < 0 { ans - cnt } else { ans + cnt * 2 } + ans.iter().collect() } } fn main() { - println!("{:?}", Solution::min_insertions("()()))((".to_string())); + println!("{:?}", Solution::remove_outer_parentheses("(()())(())(()(()))".to_string())); }