python实现leetcode之20. 有效的括号(栈)

解题思路

此处撰写解题思路
碰到左括号推入栈
碰到右括号时,把栈顶元素拿出来看是不是配对
遍历完字符串栈不空表明有没有被匹配的左括号
https://leetcode-cn.com/problems/valid-parentheses/

代码

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        match = {
            '}': '{',
            ']': '[',
            ')': '(',
        }
        stack = []
        idx, length = 0, len(s)
        while idx < length:
            if s[idx] in '([{':
                stack.append(s[idx])
                idx += 1
            else:
                if not stack:
                    return False
                elif stack.pop() != match[s[idx]]:
                    return False
                else:
                    idx += 1
        return len(stack) == 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容