【leetcode】20. Valid Parentheses

本文通过使用栈数据结构解决括号匹配问题,提供了一个简洁有效的算法实现方案,并附带详细的代码示例。

一、题目描述(最长公共前缀)

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

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.

给定一个只包含字符'(',')','{','}','[',']'的字符串,确定输入字符串是否有效。
如果输入字符串有效:
1.必须使用相同类型的括号关闭左括号。
2.必须以正确的顺序关闭左括号。
请注意,空字符串也被视为有效。

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

二、题目分析

括号的匹配问题,考虑数据结构使用栈,后进先出,如果栈为空或者括号和当前栈顶符号不匹配,就入栈,如果右括号和当前栈顶符号匹配,就弹出栈顶元素

注意:要满足查询的字符串在字典中(是左括号),不然会报错······

三、代码实现

class Solution:
    def isValid(self,s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        dict = {'(': ')', '{': '}', '[': ']'}
        for i in range(len(s)):
            if len(stack) == 0:
                stack.append(s[i])
            elif stack[-1] in dict and dict[stack[-1]] == s[i]:
                #要满足查询的字符串在字典中,不然会报错········
                stack.pop()
            else:
                stack.append(s[i])
        return stack == []

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值