leetcode-20 有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
    1、左括号必须用相同类型的右括号闭合。
    2、左括号必须以正确的顺序闭合。

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

示例 1:

输入: "()"
输出: true
示例 2:

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

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

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

思路:使用栈后进先出的特性先将'('、'['、 '{' 存进去,当遇到')'、']'、 '}' 时则弹出来。

解题代码:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack1=[]
        length=0
        for i in s:
            if  i == '(' or i ==  '[' or i ==  '{':
                stack1.append(i)
                length+=1
            elif i ==  ')':
                if length==0:
                    return False
                else: 
                    if stack1[length-1] == '(':
                        stack1.pop()
                        length-=1
                    else:
                        stack1.append(i)
                        length+=1

            elif  i ==  ']' :
                if length==0:
                    return False
                else:                     
                    if stack1[length-1] == '[':
                        stack1.pop()
                        length-=1
                    else:
                        stack1.append(i)
                        length+=1
            elif i == '}':
                if length==0:
                    return False
                else: 
                    if stack1[length-1] == '{':
                        stack1.pop()
                        length-=1

                    else:
                        stack1.append(i)
                        length+=1

        if stack1:
            # print '0'
            return False
        else:
            # print '1'
            return True
  


猜你喜欢

转载自blog.csdn.net/u012474535/article/details/80170269