Regular Bracket Sequence

本文探讨了如何从一个包含左括号和右括号的字符串中移除部分字符,以形成最长的有效括号序列。文章提供了一段C++代码示例,用于计算并输出该序列的最大可能长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

5637: Regular Bracket Sequence

时间限制: 1 Sec   内存限制: 128 MB
提交: 44   解决: 27
[ 提交][ 状态][ 讨论版]

题目描述

A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.

One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

输入

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.

输出

Output the maximum possible length of a regular bracket sequence.

样例输入

(()))(

样例输出

4
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e6+10;
char s[maxn];
int main()
{
    while(scanf("%s",s)!=EOF)
    {
        int len=strlen(s);
        int l=0,r=0;
        for(int i=0;i<len;i++)
        {
            if(s[i]=='(')
                l++;
            if(s[i]==')'&&l>0)
            {
                l--;
                r++;
            }
        }
        printf("%d\n",2*r);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值