20. Valid Parentheses

20. Valid Parentheses

description:
20. Valid Parentheses
题解:
solution1:
声明一个栈,从头到尾遍历一遍字符串,如果遇到左括号则压栈,遇到右括号则取栈顶元素与当前遍历的元素进行匹配,若匹配则继续遍历字符串,若不匹配直接返回false,只得到字符串遍历结束。判断当前栈是否为空,若为空则返回True,若不为空则返回False。除此之外还需要注意一些特殊情况的处理。
以下为python3代码

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dict = {}
        dict['('] = ')'
        dict['['] = ']'
        dict['{'] = '}'
        if len(s) == 0:
            return True
        stack = []
        list_str = list(s)
        for i in range(len(list_str)):
            if list_str[i] == '(' or list_str[i] == '[' or list_str[i] == '{':
                stack.append(list_str[i])
            elif list_str[i] == ')' or list_str[i] == ']' or list_str[i] == '}':
                if len(stack) == 0:
                    return False
                last = stack[len(stack)-1]
                if dict[last] == list_str[i]:
                    stack.pop()
                else:
                    return False
            else:
                return False
        if len(stack) == 0:
            return True
        else:
            return False