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)