有效的括号(匹配成对括号) Python实现

原文链接:【力扣】20.有效的括号–Python实现

【题目描述】
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: “()”
输出: true

示例 2:
输入: “()[]{}”
输出: true

示例 3:
输入: “(]”
输出: false

示例 4:
输入: “([)]”
输出: false

示例 5:
输入: “{[]}”
输出: true

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

【解题思路】
用栈来解决这道题,当遇到前括号的时候就入栈,当遇到后括号的时候就判断栈是否为空且栈顶元素是否是对应的括号;当结束以后如果栈为空则返回True,否则False。用Python实现的代码如下:

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

发表评论