博客
关于我
LeetCode--020--括号匹配
阅读量:793 次
发布时间:2023-01-31

本文共 742 字,大约阅读时间需要 2 分钟。

为了判断一个包含不同类型括号的字符串是否有效,我们可以使用栈数据结构。栈可以帮助我们跟踪括号的顺序,确保每个左括号都能被正确闭合。

输入包括六种括号字符:'('、')'、'{'、'}'、'['、']'。有效字符串要求左括号必须以正确的顺序和类型闭合。具体来说:

  • 每次遇到左括号,压入栈。
  • 每次遇到右括号,检查栈是否为空:
    • 如果栈为空,字符串无效。
    • 如果栈不为空,弹出栈顶字符,检查是否对应正确的左括号。
  • 遍历完整个字符串后,栈必须为空才表示闭合顺序正确。
  • 实现代码:

    class Solution:    def isValid(self, s: str) -> bool:        stack = []        for c in s:            if c in '({[':                stack.append(c)            elif c in ')]}':                if not stack:                    return False                top = stack.pop()                if (c == ')' and top != '(') or (c == '}' and top != '{') or (c == ']' and top != '['):                    return False        return len(stack) == 0

    这个方法通过遍历字符串一次,检查每个字符是否正确闭合,从而确保字符串的有效性。逻辑简单且效率高,时间复杂度为 O(n),其中 n 是字符串的长度。

    转载地址:http://vlgyk.baihongyu.com/

    你可能感兴趣的文章
    LeetCode240:Search a 2D Matrix II
    查看>>
    LeetCode268.缺失数字
    查看>>
    LeetCode331.验证二叉树的前序序列化
    查看>>
    leetcode380. Insert Delete GetRandom O(1)
    查看>>
    LeetCode502
    查看>>
    leetcode507
    查看>>
    LeetCode7.整数反转 JavaScript
    查看>>
    Leetcode: Group Anagrams
    查看>>
    Leetcode: Remove Duplicates from Sorted Array II
    查看>>
    Leetcode: Spiral Matrix II
    查看>>
    LeetCode: String to Integer (atoi)
    查看>>
    Leetcode:454. 4Sum II
    查看>>
    leetcode:Minimum Depth of Binary Tree【Python版】
    查看>>
    LeetCode:Restore IP Addresses
    查看>>
    LeetCode:Subsets I II
    查看>>
    LeetCode_Lowest Common Ancestor of a Binary Search Tree (Binary Tree)
    查看>>
    LeetCode——Unique Paths
    查看>>
    LeetCode二叉树从上至下路径问题总结(112.113.437.129)
    查看>>
    leetcode出现cannot find symbol [in __Driver__.java]
    查看>>
    LeetCode动态规划训练营(1~5天)
    查看>>