Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode-20. Valid Parentheses #29

Closed
ninehills opened this issue Jul 28, 2017 · 1 comment
Closed

LeetCode-20. Valid Parentheses #29

ninehills opened this issue Jul 28, 2017 · 1 comment
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Jul 28, 2017

问题

https://leetcode.com/problems/valid-parentheses/tabs/description

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.

思路

使用stack的思想,碰到({[就压栈,碰到)}]就出栈,出栈时栈空或者遍历结束后栈不为空,则not valid

解答

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        m = {'[': ']', '{': '}', '(': ')'}
        for c in s:
            if c in m:
                stack.append(c)
            else:
                if not stack:
                    return False
                else:
                    k = stack.pop()
                    if c == m[k]:
                        continue
                    else:
                        return False
        if not stack:
            return True
        else:
            return False


print Solution().isValid("[[[{{{{(((((())))))}}}}]]]")
print Solution().isValid("[{}[{{{{({{}}((((({{}}))))))}}}}]]]")
@ninehills
Copy link
Owner Author

#4 20170729

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant