棧的實例場景

簡述

寫代碼思路:接到需求先要明確目標、而後分析過程(結合所學的基礎知識對業務進程拆分)、逐步執行、代碼實現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('(){}[]{()}'))
相關文章
相關標籤/搜索