首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 20. 有效的括号

LeetCode 20. 有效的括号

作者头像
freesan44
发布2020-02-25 17:01:25
2420
发布2020-02-25 17:01:25
举报
文章被收录于专栏:freesan44freesan44freesan44

题目

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

解题思路

用栈的概念

class Solution:
    def isValid(self, s: str) -> bool:
        inList = ["(", "{", "["]
        outList = [")", "}", "]"]
        tempList = list()
        strList = list(s)
        for each in strList:
            if each in inList:
                tempList.append(each)
            elif each in outList:
                if len(tempList) <= 0:
                    return False
                lastS = tempList[-1]
                if (lastS in inList) and (inList.index(lastS) == outList.index(each)):
                    tempList.pop()
                else:
                    return False
        if len(tempList) > 0:
            return False
        return True
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档