20. Valid Parentheses

【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)