您的位置:首页 > 产品设计 > UI/UE

Review of Codeforces 5C. Longest Regular Bracket Sequence

2014-11-13 05:21 453 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codeforces python