您的位置:首页 > 其它

LeetCode-20 valid parenthesis

2018-03-21 11:48 369 查看
题目:括号匹配问题
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.解题: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.
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        """
        根据tag给的提示,应该是用到了stack的思想
        构建一个字典,将右括号放在keys,左括号放在values
        如果s中的元素在values中,压栈append
        如果在keys中:栈为空或没有匹配的左括号,false
        其他情况false
        最终栈应该是空的,都对应的pop掉了
        """
        dict = {'}':'{',']':'[',')':'('}
        stack = []
        for ch in s:
            if ch in dict.values():
                stack.append(ch)
            elif ch in dict.keys():
                if stack == [] or dict[ch] != stack.pop():
                    return False
            else:
                return False
        return stack == []
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: