Review of Codeforces 5C. Longest Regular Bracket Sequence

来源:互联网 发布:mac pro 贴膜涂层脱落 编辑:程序博客网 时间:2024/05/01 13:33

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 = 0rep = 0for 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] = iif l:    print l, repelse :    print 0, 1


0 0
原创粉丝点击