美文网首页
leetcode 有效的括号

leetcode 有效的括号

作者: 仁安天下 | 来源:发表于2019-10-13 11:37 被阅读0次

    给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

    有效字符串需满足:

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

    示例 1:

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

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

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

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/valid-parentheses
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack=[]
            dic={"(":-1,"[":-5,"{":-10,")":1,"]":5,"}":10}
            for index,val in enumerate(s):
                if dic[val]<0:
                    stack.append(dic[val])
                else:
                    if index==0 or len(stack)==0:
                        return False
                    else:
                        
                        if stack[-1]==-1*dic[s[index]]:
                            stack.pop()
                        else:
                            return False
            print stack
                    
            if len(stack)==0:
                return True
            else:
                return False
    

    相关文章

      网友评论

          本文标题:leetcode 有效的括号

          本文链接:https://www.haomeiwen.com/subject/lwphmctx.html