【LeetCode】22. 有效的括号

本文介绍了一种使用栈数据结构来判断括号序列是否有效的方法。通过两种实现方式,一种是直接比较括号类型,另一种是利用字典提高代码可读性和可维护性。文章详细解释了算法的运行逻辑,并提供了Python代码示例。

问题描述

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

给定一个只包含字符'(',')','{','}','['和']'的字符串,判断输入字符串是否有效。
输入字符串是有效的,如果:

  • 开括号必须由相同类型的括号括起。
  • 开括号必须按正确的顺序闭合。

注意,空字符串也被认为是有效的。

输入: "()"
输出: true

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

输入: "(]"
输出: false

输入: "([)]"
输出: false

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

 

Python 实现

实现一:判断括号的有效性,最直接的方法就是使用栈,出现左括号时入栈,出现右括号时,栈顶必须是对应的左括号并弹出,不然返回 False,最后栈的大小为 0,则说明括号有效。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        stack = []
        for c in s:
            if len(stack) > 0 and stack[-1] == '(' and c == ')':
                stack.pop()    
            elif len(stack) > 0 and stack[-1] == '{' and c == '}':
                stack.pop()
            elif len(stack) > 0 and stack[-1] == '[' and c == ']':
                stack.pop()
            else:
                stack.append(c)
        
        if len(stack) == 0:
            return True
        else:
            return False

实现二:原理跟上面一样,只是通过字典将每组括号对储存起来,这样写的代码更便于拓展和维护,可读性也更强。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """

        pairs = {"(": ")", "{": "}", "[": "]"}
        stack = []
        for i in range(len(s)):
            if s[i] in pairs:
                stack.append(s[i])
            elif len(stack) > 0 and s[i] == pairs[stack[-1]]:
                stack.pop()
            else:
                return False
                
        if len(stack) == 0:
            return True
        else:
            return False
    

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值