Valid Parentheses

题目链接

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: “()”
Output: true

Example 2:

Input: “()[]{}”
Output: true

Example 3:

Input: “(]”
Output: false

Example 4:

Input: “([)]”
Output: false

Example 5:

Input: “{[]}”
Output: true

解题思路:

这道题是括号匹配题,我记得就在上周开组会的时候师姐和我们说过这是一道她面试时的一道原题,今天自己遇到,秒解出来还是很开心的。
首先,此题借用了栈的数据结构,然后去遍历这个括号字符串。首先,如果为左括号,则将其压入栈中,如果是右括号,则判断该括号对应的左括号是否在栈中,如果在,则从栈顶弹出一个,否则则返回False。
最后,判断这个栈是否为空,如果为空,则括号匹配正确,返回True,否则返回False.
so eazy~

python3代码实现:

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        for i in s:
            if i == '(' or i == '[' or i == '{':
                stack.append(i)

            elif (i == ')' and '(' in stack) or (i == ']' and '[' in stack) or (i == '}' and '{' in stack):
                stack.pop()
            else:
                return False
        if len(stack) == 0:
            return True
        else:
            return False
        

实现结果:

Valid Parentheses