Valid Parentheses python题解

Valid Parentheses python题解

题目描述

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
经典的利用栈判定括号匹配的问题:这里用python实现,python中并没有C++的stack和queue,但是二者的操作均可用列表来实现,主要是利用了列表的pop()操作,列表的弹出很灵活,如下所示:

Valid Parentheses python题解_第1张图片

算法如下:

从左向右遍历字符串:

若为左括号则压入栈(append),若为右括号则将栈顶元素与该括号进行匹配,若匹配则将该左括号出栈,若不匹配则直接返回假,遍历完成后如果栈为空则为正确括号序列,否则为不匹配括号序列

代码如下:

def isValid(s):
    matchDict={'(':')','[':']','{':'}'}
    strLen=len(s)
    stackList=[]
    for i in range(strLen):
        if s[i] not in matchDict.keys() and len(stackList)==0:
            return False 
        elif s[i] in matchDict.keys():
            stackList.append(s[i])
        elif s[i]==matchDict[stackList[-1]]:
            stackList.pop()
        else: return False
    if len(stackList)==0:
        return True
    else: return False

注意for循环的第一个判断条件,遍历到右括号并且栈为空时直接返回假,如果不加这一句的话,类似 ‘)’, ‘([]’这种序列会出现下标越界的情况,因为在栈为空时取了栈顶元素

欢迎交流更加简洁高效的解法

你可能感兴趣的:(LeetCode,python,stack)