Leecode 20.有效的括号

题目

在这里插入图片描述
添加链接描述

基本思路

在这里解题使用到

  • 遍历字符串
  • 如果当前字符串为"(","{","[",则加入到栈中
  • 如果当前字符串为"}",")","]",
  • (1) 如果此时栈为空,则返回False
  • (2) 若栈不为空,且为栈顶元素对应的右半括号,则取出栈顶元素,继续循环
  • (3) 若不为栈顶元素对应的右半边括号,返回False
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        #创建空列表
        stack=[]
        #创建一个字典       
        map={"{":"}","(":")","[":"]"}
        for char in s:
            #当元素是键{ ( [
            if char in map:
            #将元素添加到列表
                stack.append(map[char])
            else:
            #当长度不为零
                if len(stack) != 0:
                #列表最后一个被删除,并且最后一个元素的值赋给top_element
                    top_element=stack.pop()
                    if char!=top_element:
                        return False
                    else:
                        continue
                else:
                    return False
        #判断列表是否为空
        return len(stack)==0

在这里插入图片描述

发布了52 篇原创文章 · 获赞 5 · 访问量 3973

猜你喜欢

转载自blog.csdn.net/Pang_ling/article/details/105039928
今日推荐