美文网首页
Q20 Valid Parentheses

Q20 Valid Parentheses

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:31 被阅读3次

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.

解题思路:

模拟栈的操作,如果是(、[、},则入栈;如果是 )、]、},则出栈。如果匹配正确,最后栈为空,说明字符串有效。

Python实现:
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) == 0:
            return False
        if s[0] != '(' and s[0] != '[' and s[0] != '{':
            return False
        stack = []  # 模拟栈的操作
        for i in range(len(s)):
            if s[i] == '(' or s[i] == '[' or s[i] == '{':
                stack.append(s[i])
            else:
                if len(stack) == 0:  # 栈中没有匹配 (、[、{ 的字符
                    return False
                ch = stack.pop()
                if ch == '(' and s[i] != ')' or ch == '[' and s[i] != ']' or ch == '{' and s[i] != '}':
                    return False
        if len(stack) == 0:
            return True
        else:
            return False

a = '[])'
b = Solution()
print(b.isValid(a))  # false

相关文章

网友评论

      本文标题:Q20 Valid Parentheses

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