前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q20 Valid Parentheses

Q20 Valid Parentheses

作者头像
echobingo
发布2018-04-25 16:42:20
5200
发布2018-04-25 16:42:20
举报
文章被收录于专栏:Bingo的深度学习杂货店

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

解题思路:

模拟栈的操作,如果是(、[、},则入栈;如果是 )、]、},则出栈。如果匹配正确,最后栈为空,说明字符串有效。

Python实现:
代码语言:javascript
复制
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) == 0:
            return False
        if s[0] != '(' and s[0] != '[' and s[0] != '{':
            return False
        stack = []  # 模拟栈的操作
        for i in range(len(s)):
            if s[i] == '(' or s[i] == '[' or s[i] == '{':
                stack.append(s[i])
            else:
                if len(stack) == 0:  # 栈中没有匹配 (、[、{ 的字符
                    return False
                ch = stack.pop()
                if ch == '(' and s[i] != ')' or ch == '[' and s[i] != ']' or ch == '{' and s[i] != '}':
                    return False
        if len(stack) == 0:
            return True
        else:
            return False

a = '[])'
b = Solution()
print(b.isValid(a))  # false
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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