(python刷题)leetcode 第20题:有效的括号

题目在leetcode上的链接为:
https://leetcode-cn.com/problems/valid-parentheses/

题目描述
在这里插入图片描述

解题思路
使用栈进行解题。遍历字符串,如果遇到左括号就入栈,遇到右括号就出栈并比较出栈的左括号是否与该右括号匹配,最后如果遍历完字符串且栈为空,说明字符串为有效括号。
判断左右括号是否匹配可以使用 dict 建立括号的匹配关系:

dic = {"(": ")", "{": "}", "[": "]"}

python 中使用列表实现栈:

stack = []

# 入栈
stack.qppend

# 出栈并获取栈顶元素
stack.pop()

# 栈为空
len(stack) == 0

复杂度分析:
需要遍历一次字符串,时间复杂度为 o(n)
需要使用栈来存放字符串中的左括号,空间复杂度为 o(n)

python代码

class Solution:
    def isValid(self, s: str) -> bool:
        if s == "":
            return True
        # 字符串元素数目为奇数
        if len(s) % 2 == 1:
            return False
        dic = {"(": ")", "{": "}", "[": "]"}
        stack = []
        for i in range(len(s)):
            # s[i]为左括号则入栈
            if s[i] in dic:
                stack.append(s[i])
            else:
                # s[i]为右括号且栈为空,或者栈顶的左括号与右括号s[i]不匹配
                if len(stack) == 0 or dic[stack.pop()] != s[i]:
                    return False
        # 遍历字符串结束后,如果栈不为空,则还有左括号未匹配,为无效括号,否则为有效括号
        return len(stack) == 0
发布了37 篇原创文章 · 获赞 6 · 访问量 5378

猜你喜欢

转载自blog.csdn.net/qq_37891889/article/details/104371292