Leetcode刷题笔记47-有效的括号

1. 题目

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "([)]"
输出: false

2. 解答

python3

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        left = ["(", "{", "["]
        right = [")", "}", "]"]
        stack = []
        for i in range(len(s)):
            if s[i] in left:
                stack.append(s[i])
            elif s[i] in right:
                if len(stack) != 0:
                    if stack[-1] in left:
                        id_l = left.index(stack[-1])
                        id_r = right.index(s[i])
                        if id_l != id_r:
                            return False
                        stack.pop()
                    else: return False
                else: stack.append(s[i])
        if len(stack) == 0:
            return True
        else:
            return False
# string = "()[]{}"
# string = "]"
string = ")}{({))[{{[}"
s = Solution().isValid(string)
print(s)

猜你喜欢

转载自www.cnblogs.com/Joyce-song94/p/9194449.html