栈的实例场景

简述

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

目标

判断字符串中的符号是否可以形成有效组合,示例:

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

代码

代码块

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

代码

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('(){}[]{()}'))
转载引用请标明出处,本博出自喝了少不如不喝的博客https://home.cnblogs.com/u/wangdadada
原文地址:https://www.cnblogs.com/wangdadada/p/12112988.html