栈的应用——括号匹配

Description

在实际编程中,我们经常会嵌套使用括号,如“{}”、“[]” 、 “()”,如果括号太多,可能会出现括号不匹配的情况,比如“(as))”、“{(bcd})”等。现希望你们编写一个程序,判断输入的一段语句中的括号是否匹配。必须使用栈实现这个功能。

Input
字符串s,s是由{}、[]、()以及数字字母组成的字符串。

Output
若括号使用规范且匹配,输出“True”;否则输出“False”。

Sample Input 1

4Print(abc[0]+’This is a {}’)
Sample Output 1

True
Sample Input 2

“{abc}{de}(f)[(g)”
Sample Output 2

False
Sample Input 3

0{abc}{de}(f)[(g)]96
Sample Output 3

True
Sample Input 4

{aaa)}
Sample Output 4

False
Sample Input 5

88778print(){}{}{{(}})
Sample Output 5

False

coding:
要点1:不需要的字母不入栈即可
要点2:处理完后栈应该为空,否则需返回False

def parenthesis_matching(temp_list):
    for i in range(len(temp_list)):
        temp_ele = temp_list[i]
        if temp_ele == '{' or temp_ele == '[' or temp_ele == '(':
            stack.append(temp_ele)
        elif temp_ele == '}':
            if stack.pop() != '{':
                return False
        elif temp_ele == ']':
            if stack.pop() != '[':
                return False
        elif temp_ele == ')':
            if stack.pop() != '(':
                return False

    if len(stack) == 0:
        return True
    else:
        return False


def output(pending_list):
    if parenthesis_matching(pending_list):
        print("True")
    else:
        print("False")


stack = []

needed_list = input()

output(needed_list)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值