Review of Codeforces 5C. Longest Regular Bracket Sequence

5C. Longest Regular Bracket Sequence

This is yet another problem dealing with regular bracket sequences.

We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.

You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.


This task can be solved by using stacks. when we get '(', we push it to stack. When we get ')', there are two possible solution, 1st: there are only one element in the stack(We previously set s[0] = -1, because to ensure the lenth can ba corrected when we use the index to get the lenth of the target sequence) and assign s[0] = i, which means that the start point to measure length has shiftd to position i. otherwise, we can pop one element from stack and using i - s[-1] to get the length of sequence. the source code is as follows:

s = [-1]
l = 0
rep = 0

for i, c in enumerate(raw_input()):
    if c == '(':
        s.append(i)
    else:
        if len(s) > 1:
            s.pop()
            temp = i - s[-1]
            if temp > l:
                l = temp
                rep = 1
            elif temp == l:
                rep += 1
        else:
            s[0] = i
if l:
    print l, rep
else :
    print 0, 1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值