LeetCode算法题——20. Valid Parentheses

来源:互联网 发布:大连美工培训班哪里好 编辑:程序博客网 时间:2024/06/13 17:55
题目

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

采用栈机制,对于每个进栈元素都与栈顶元素进行匹配,若匹配成功,这栈顶元素弹出,若匹配不成功,则进栈

Pyhon实现:

# -*- coding:utf-8 -*-class Solution(object):    def isValid(self, s):        """        :type s: str        :rtype: bool        """        brackets=[]        for i in range(0,s.__len__()):            pipei=False            if len(brackets)!=0:                b=brackets.pop()                if b=='(':                    if s[i]==')':                        pipei=True                elif b=='{':                    if s[i]=='}':                        pipei=True                elif b=='[':                    if s[i]==']':                        pipei=True                if pipei==False:                    brackets.append(b)                    brackets.append(s[i]);            else:                brackets.append(s[i])        if len(brackets)==0:            return True        else:            return False    if __name__=="__main__":    s=Solution()    res=s.isValid("{[)(]}")    print(res)    


0 0
原创粉丝点击