zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

921. 使括号有效的最少添加

2023-02-18 16:34:57 时间

921. 使括号有效的最少添加

Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

It is the empty string, or
It can be written as AB (A concatenated with B), where A and B are valid strings, or
It can be written as (A), where A is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

 

给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效。

从形式上讲,只有满足下面几点之一,括号字符串才是有效的:

它是一个空字符串,或者
它可以被写成 AB (A 与 B 连接), 其中 A 和 B 都是有效字符串,或者
它可以被写作 (A),其中 A 是有效字符串。
给定一个括号字符串,返回为使结果字符串有效而必须添加的最少括号数

 

示例 1:

  输入:"())"
  输出:1
示例 2:

    输入:"((("
输出:3
示例 3:

  输入:"()"
  输出:0
示例 4:

  输入:"()))(("
  输出:4

 

#include<iostream>
#include<bits/stdc++.h>
#include<cstring>
using namespace std;
int minAddToMakeValid(string str) {
    int len=str.length();
    stack<char> st;
    for (int i = 0; i < len; i++)
    {
        if (!st.empty())
        {
            if ((st.top()=='(')&&(str[i]==')'))
            {
                st.pop();
            }else
            {
                st.push(str[i]);
            }
        }else
        {
            st.push(str[i]);
        }
    }
    return st.size();
}


int main(){
    string str;
    cin>>str;
    cout<<minAddToMakeValid(str)<<endl;
}

方法一: 平衡法
思路和算法

保证左右括号数量的 平衡: 计算 '(' 出现的次数减去 ')' 出现的次数。如果值为 0,那就是平衡的,如果小于 0,就要在前面补上缺少的 '('。

计算 S 每个前缀子数组的 平衡度。如果值是负数(比如说,-1),那就得在前面加上一个 '('。同样的,如果值是正数(比如说,+B),那就得在末尾处加上 B 个 ')' 。

class Solution {
    public int minAddToMakeValid(String S) {
        int ans = 0, bal = 0;
        for (int i = 0; i < S.length(); ++i) {
            bal += S.charAt(i) == '(' ? 1 : -1;
            // It is guaranteed bal >= -1
            if (bal == -1) {
                ans++;
                bal++;
            }
        }

        return ans + bal;
    }
}