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

LeetCode - 020

作者头像
咸鱼学Python
发布2019-06-18 19:46:33
3290
发布2019-06-18 19:46:33
举报
文章被收录于专栏:咸鱼学Python咸鱼学Python
原题

https://leetcode.com/problems/valid-parentheses/

题干

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

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.

Example 1:

Input: "()" Output: true Example 2:

Input: "()[]{}" Output: true Example 3:

Input: "(]" Output: false Example 4:

Input: "([)]" Output: false Example 5:

Input: "{[]}" Output: true

这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的这是凑字数的

代码语言:javascript
复制
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        while '[]' in s or '()' in s or '{}' in s:
            s = s.replace('[]','').replace('()','').replace('{}','')
        return len(s) == 0
代码语言:javascript
复制
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        left = '({['
        right = ']})'
        for chart in s:
          if chart in left:
            stack.append(chart)
          if chart in right:
            if not stack:
              return False
            temp = stack.pop()
            if chart == '}' and temp != '{':
              return False
            if chart == ']' and temp != '[':
              return False
            if chart == ')' and temp != '(':
              return False
        return stack == []
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 咸鱼学Python 微信公众号,前往查看

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

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

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