checkio Remove Brackets

题目:
Before solving this mission, you can try to solve the “Brackets” mission.

Your task is to restore the balance of open and closed brackets by removing the unnecessary ones, while trying to use the minimum number of deletions.

Only 3 types of brackets (), [] and {} can be used in the given string.

Only a parenthesis can close a parenthesis. That is, in this expression “(}” - the brackets aren’t balanced. In an empty string, i.e., in a string that doesn’t contain any brackets - the brackets are balanced, but removing all of the brackets isn’t considered to be an optimal solution.

If there are more than one correct answer, then you should choose the one where the character that can be removed is closer to the beginning. For example, in this case “[(])”, the correct answer will be “()”, since the removable brackets are closer to the beginning of the line.

Input: A string of characters () {} []

Output: A string of characters () {} []

Example:
remove_brackets(’(()()’) == ‘()()’
remove_brackets(’[][[[’) == ‘[]’
remove_brackets(’[[(}]]’) == ‘[[]]’
remove_brackets(’[[{}()]]’) == ‘[[{}()]]’
remove_brackets(’[[[[[[’) == ‘’
链接:
https://py.checkio.org/en/mission/remove-brackets/

代码:

def remove_brackets(line: str) -> str:
    a = line
    aa = a[::-1]
    b = list(enumerate(aa))
    def fd(b,s):
        x =[]
    	for i in range(0,len(b)-1):
    		for j in range(i+1, len(b)):
    			if b[i][1] == s[1] and b[j][1] == s[0] and b[i][0] not in x and b[j][0] not in x:
    				x.append(b[i][0])
    				x.append(b[j][0])
    	q = []
    	for i in range(0,int(len(x)/2)):
    		q.append([x[2*i],x[2*i+1], s])
    	return q
    mm =[]
    mm.extend(fd(b,'[]'))
    mm.extend(fd(b,'()'))
    mm.extend(fd(b,'{}'))
      
    qq = sorted(mm, key = lambda x:x[0], reverse= False)
    bb = qq
    for i in range(0, len(qq)-1):
    	for j in range(i+1, len(qq)):
    		if qq[j][0] < qq[i][1] and qq[j][1] > qq[i][1] and qq[j][2]!=qq[i][2]:
    			bb.remove(qq[j])
    yy = []
    for i in bb:
    	yy.append(i[0])
    	yy.append(i[1])
    yy = sorted(yy)   
    y = []
    for i in yy:
    	y.append(aa[i])
    mm = ''.join(y)
    r = mm[::-1]
    return r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值