Check parentheses ‘(’,‘)’

题目

Given a string, write check(s) to check if the opening brackets ( match closing brackets ). Here we only
consider this type of parenthesis pairs. For example,
Matched pairs: (abc), (a(b(c))), expected return: True.
Unmatched pairs: (abc, (a))(, expected return: False.

方法一(删除相邻'(' 和’)' ):#实在有点傻

'(' 和’)' 的数目不一样多,not match

最后一个符号是'(',not match

重复删除相邻的'(' 和’)',如果一直删到空,则matach,如果剩下的最后一个符号还是‘(’,not match

def check(s):
    list=[] #to collect all parenthese
    odd=0
    even=0
    for ele in s:
        if ele in ('(',')'):
            if ele=='(':
                odd+=1
            else:
                even+=1
            list.append(ele)
    if odd!=even:
        return False
    else:
        return checkcore(list)
def checkcore(list):
    if len(list)==0:
        return True
    if list[-1]=='(':
        return False
    for i in range(len(list)-1):
        if list[i]=='(' and list[i+1]==')':
            del list[i]
            del list[i]
            break
    return checkcore(list)

def main3():
    s1='(abc)'
    s2='(a(b(c)))'
    s3='(abc'
    s4='(a)))()'
    print(check(s1))
    print(check(s2))
    print(check(s3))
    print(check(s4))

main3()

方法二(使用stack)

遇到打开的括号就往stack里面存一个,遇到关闭的括号且stack不为空就stack.pop(),

最后stack为空,则为True。

def check1(s):
    stack=[]
    for ele in s:
        if ele=='(':
            stack.append(ele)
        elif ele==')':
            if (len(stack)>0):
                stack.pop()
            else:
                return False
    if len(stack)==0:
        return True
    else:
        return False

def main3():
    s1='(abc)'
    s2='(a(b(c)))'
    s3='(abc'
    s4='(a)))()'
    print(check1(s1))
    print(check1(s2))
    print(check1(s3))
    print(check1(s4))

main3()

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值