LeetCode--Valid Parentheses

来源:互联网 发布:java 管理系统框架 编辑:程序博客网 时间:2024/06/07 13:07
题目:
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.
给定一个字符串包含()[]{}字符,若能满足括号对称,则返回true,否则返回false
解题思路:
这个题目很明显需要用堆栈的方式来解决。遍历字符串,若堆栈中的最后一个字符跟当前的字符对称,则弹出堆栈中的最后一个字符;否则将当前字符加入堆栈
代码如下:
class Solution(object):    def isValid(self, s):        """        :type s: str        :rtype: bool        """        stack = []        dict = {            '(': ')',            '[': ']',            '{': '}'                    }        for i in range(len(s)):            lenth = len(stack)            if lenth==0:                stack.append(s[i])            else:                try:                    if dict[stack[lenth-1]]==s[i]:                        stack.pop()                    else:                        stack.append(s[i])                except:                    stack.append(s[i])        if len(stack)==0:            return True        else:            return False