LeetCode_Everyday:020 Valid Parentheses

LeetCode_Everyday:020 Valid Parentheses


LeetCode Everyday:坚持价值投资,做时间的朋友!!!

题目:

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

有效字符串需满足:

1. 左括号必须用相同类型的右括号闭合。
2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例:

  • 示例 1:
    输入: "()"
    输出: true
    
  • 示例 2:
    输入: "()[]{}"
    输出: true
    
  • 示例 3:
    输入: "(]"
    输出: false
    
  • 示例 4:
    输入: "([)]"
    输出: false
    
  • 示例 5:
    输入: "{[]}"
    输出: true
    

代码

方法一: 堆栈 题解

执行用时:32 ms, 在所有 Python3 提交中击败了97.36%的用户
内存消耗:13.8 MB, 在所有 Python3 提交中击败了5.22%的用户

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {')':'(',']':'[','}':'{'}
        stack = []
        for i in s:
            if stack and i in dic:
                if stack[-1] == dic[i]: stack.pop()
                else: return False
            else: stack.append(i)
            
        return not stack

"""
For Example:    input:    s = "{[]}"
               output:    true
"""
s = "{[]}"
                
solution = Solution()
result = solution.isValid(s)
print('输出为:', result)

参考

  1. https://leetcode-cn.com/problems/valid-parentheses/solution/zhu-bu-fen-xi-tu-jie-zhan-zhan-shi-zui-biao-zhun-d/

此外

  • 原创内容转载请注明出处
  • 请到我的GitHub点点 star
  • 关注我的 CSDN博客
  • 关注我的哔哩哔哩
  • 关注公众号:CV伴读社

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章