题解 | #有效括号序列#

有效括号序列

http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2

解题思路:

  1. 非常经典的栈的使用案例 - 括号匹配,只不过这道题难度降低了很多
  2. 判断是左括号就入栈
  3. 碰到右括号的时候,从栈顶弹出一个元素,看右括号是否与栈顶元素的左括号匹配,不匹配就返回False
  4. 整个入栈出栈结束以后看栈内是否还有元素,还有元素就说明匹配失败
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return bool布尔型
#
class Solution:
    def isValid(self , s: str) -> bool:
        # write code here
        if not s:
            return False
        lst = []
        for i in s:
            if i == '{' or i == '(' or i == '[':
                lst.append(i)
            else:
                if lst == []:
                    return False
                if i == '}':
                    if lst.pop() != '{':
                        return False
                elif i == ')':
                    if lst.pop() != '(':
                        return False
                elif i == ']':
                    if lst.pop() != '[':
                        return False
        if lst == []:
            return True
        else:
            return False
全部评论
你好,我是个新手,请问def isValid(self , s: str) -> bool:是什么意思?
点赞 回复 分享
发布于 2022-06-17 21:53

相关推荐

ros275229:社团删了吧,cf因该1200才勉强入门吧,也删了,你可以写算法刷了多少道,都比这个好
点赞 评论 收藏
分享
评论
7
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务