21 leetcode - Valid Parentheses

来源:互联网 发布:oracle sql优化书籍 编辑:程序博客网 时间:2024/05/22 15:41
#!/usr/bin/python# -*- coding: utf-8 -*-'''英文:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.中文:括号配对,没有配对成功的话返回False,成功返回True举例:The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.'''class Solution(object):    def isValid(self,s):        length = len(s)        if length & 1 or length == 0:  #字符串个数为奇数/字符串为空            return False        ret = True        stack = []        left = ('{','(','[')        right = ('}',')',']')        for i in s:            if i in left:                stack.append(i)            elif i in right:                if len(stack) < 1:                    ret = False                    break                if stack.pop() == left[right.index(i)]:                    continue                else:                    ret = False                    break            else:                ret = False                break        if len(stack) > 0:  #有剩余的话,说明无法配对            ret = False        return ret
0 0
原创粉丝点击