美文网首页
20. Valid Parentheses

20. Valid Parentheses

作者: Chiduru | 来源:发表于2019-03-25 17:24 被阅读0次

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

    An input string is valid if:

    Open brackets must be closed by the same type of brackets.
    Open brackets must be closed in the correct order.
    Note that an empty string is also considered valid.

    【Idea】

    准备一个list和一个字典:
    字典存储每个左括号对应的右括号,相当于映射作用;
    list做栈,按顺序遍历时,出现左括号就放入栈内,出现右括号时弹出栈顶元素,并与它在字典中对应的value值比较,不同时直接return False

    【Solution】

    class Solution:
        def isValid(self, s: str) -> bool:
            str_list = []
            dic = {
                '(': ')',
                '[': ']',
                '{': '}',
            }
            for i in s:
                if i in ['(', '[', '{']:
                    str_list.append(i)
                elif i in [')', ']', '}']:
                    if str_list != []:
                        temp = str_list.pop()
                        if i != dic.get(temp, None):
                            return False
                    else:
                        return False
            if str_list == []:
                return True
            return False
    
    

    相关文章

      网友评论

          本文标题:20. Valid Parentheses

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