栈的实例场景

简述

写代码思路:接到需求先要明确目标、而后分析过程(结合所学的基础知识对业务进程拆分)、逐步执行、代码实现app

目标

判断字符串中的符号是否能够造成有效组合,示例:this

#()\[]\{} 返回True
#([{}]) 返回True
#([)] 返回false
# (){}[] 返回True
#((]) 返回falsespa

代码

代码块code

'''
while str_raw != "":
    if ...:
    elif...:
        if...:
        else:
if stack == []:
    return True
else:
    return False
'''

代码blog

def check_brase(str_raw):
    if str_raw == "":
        return True

    #定义一个空列表,模拟栈。
    stack = []
    
    while str_raw != "":
        thisChar = str_raw[0]
        #若是本次循环的第一个字符是左括号,将其压栈
        if thisChar == "(" or thisChar == "{" or thisChar == "[":
            stack.append()
        elif thisChar == ")" or thisChar == "}" or thisChar == ']':
            len_stack = len(stack)
            if len_stack == 0:
                return False
            else:
                if thisChar == "(" and stack[len_stack-1] == "(":
                    stack.pop(len_stack-1)
                elif thisChar == "]" and stack[len_stack-1] == "[":
                    stack.pop(len_stack-1)
                elif thisChar == "]" and stack[len_stack-1] == "{":
                    stack.pop(len_stack-1)
                else:
                    return False
    if stack == []:
        return True
    else:
        return False
print(check_brace('(){}[]{()}'))
相关文章
相关标签/搜索