给定一个由 '('
和 ')'
括号组成的字符串 S
,我们需要添加最少的括号( '('
或是 ')'
,可以在任何位置),以使得到的括号字符串有效。
从形式上讲,只有满足下面几点之一,括号字符串才是有效的:
- 它是一个空字符串,或者
- 它可以被写成
AB
(A
与B
连接), 其中A
和B
都是有效字符串,或者 - 它可以被写作
(A)
,其中A
是有效字符串。
给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数。
输入: "())" 输出: 1
输入: "(((" 输出: 3
输入: "()" 输出: 0
输入: "()))((" 输出: 4
S.length <= 1000
S
只包含'('
和')'
字符。
impl Solution {
pub fn min_add_to_make_valid(s: String) -> i32 {
let mut s = s;
while s.contains("()") {
s = s.replace("()", "");
}
s.len() as i32
}
}
impl Solution {
pub fn min_add_to_make_valid(s: String) -> i32 {
let mut stack: Vec<char> = Vec::new();
for ch in s.chars() {
if ch == ')' && stack.ends_with(&['(']) {
stack.pop();
} else {
stack.push(ch);
}
}
stack.len() as i32
}
}
impl Solution {
pub fn min_add_to_make_valid(s: String) -> i32 {
let mut left = 0;
let mut right = 0;
for ch in s.chars() {
if ch == '(' {
left += 1
} else if left > 0{
left -= 1
} else {
right += 1
}
}
left + right
}
}