LeetCode#20. Valid Parentheses

作者: 夹小欣 | 来源:发表于2017-11-06 13:19 被阅读4次

今天是两道easy难度的题,印象中是当初学数据结构时候讲过的栗子。
括号匹配,用栈来处理,需要注意一下越界问题,

class Solution(object):
    def isValid(self, s):
        stack_left = []
        if len(s) <= 1:
            return False
        
        for char in s:
            n = len(stack_left)
#这个地方用or和用多个elif 的运行时间差距很大,判断机制的引入不是没道理
            if char == '(' or char =='{' or char =='[':
                stack_left.append(char)
                continue
            if n>0:
                if char ==')' :
                    if stack_left[-1]=='(':
                        stack_left.pop()
                    else:
                        return False
                elif char =='}' :
                    if stack_left[-1]=='{':
                        stack_left.pop() 
                    else:
                        return False
                elif char ==']' :
                    if stack_left[-1]=='[':
                        stack_left.pop() 
                    else:
                        return False
            else:
                return False
        if len(stack_left) == 0:
            return True
        else:
            return False
        ```

相关文章

网友评论

    本文标题:LeetCode#20. Valid Parentheses

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