LintCode:有效的括号序列

来源:互联网 发布:sql server 按天分组 编辑:程序博客网 时间:2024/06/05 04:32

LintCode:有效的括号序列

用栈解决,如果字符是 ( or { or [ 就进栈,否则就出栈,判断是否匹配即可。

class Solution:    # @param {string} s A string    # @return {boolean} whether the string is a valid parentheses    def isValidParentheses(self, s):        # Write your code here        if len(s) % 2 == 1 or len(s) == 0:            return False        L1 = []        for ch in s:            if ch == '{' or ch == '(' or ch == '[':                L1.append(ch)            else:                if ch == '}':                    if L1:                        if L1.pop() == '{':                            pass                        else:                            return False                    else:                        return False                if ch == ']':                    if L1:                        if L1.pop() == '[':                            pass                        else:                            return False                    else:                        return False                if ch == ')':                    if L1:                        if L1.pop() == '(':                            pass                        else:                            return False                    else:                        return False        if L1:            return False        return True
0 0
原创粉丝点击