首页 > 学院 > 开发设计 > 正文

Leetcode 20. Valid Parentheses

2019-11-08 02:05:53
字体:
来源:转载
供稿:网友
题目:

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.

思路:使用数据结构栈。碰到左操作符就进栈,右操作符就判断栈是否为空,空则return Fasle,不空则pop下是不是对应的左操作符,不是就return False。最后判断栈是否空,不空return False,否则return True.

class Solution(object):    def isValid(self, s):        """        :type s: str        :rtype: bool        """        stack = []        lf = ['(','{','[']        rt = [')', '}',']']        for i in s:            if i in lf:                stack.append(i)            elif i in rt:                ind = rt.index(i)                if len(stack)==0 or stack.pop()!=lf[ind]:return False        if len(stack)!=0 :return False        return True


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表