美文网首页程序人生程序员我爱编程
LeetCode习题解析-Valid Parentheses

LeetCode习题解析-Valid Parentheses

作者: Kindem | 来源:发表于2018-03-19 17:20 被阅读5次

转自Kindem的博客

题目

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.

给出一个只由大中小括号构成的字符串,看字符串是否满足左右括号包裹匹配的规则

解法

核心思想就是使用栈:

  1. 建立栈
  2. 遍历字符串,如果是左括号,将其入栈,如果是右括号,将其与栈顶的左括号比较,如果是一对则将栈顶元素出栈,如果不是就返回False
  3. 遍历完成后如果栈中还有元素,返回False

python3代码:

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

相关文章

网友评论

    本文标题:LeetCode习题解析-Valid Parentheses

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