Leetcode 20 - Valid Parentheses

题目描述

Leetcode 20 主要考察了栈的思想。

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

规则如下:

  1. 打开的括号,必须被相同类型的括号关上。
  2. 打开的括号,必须被按照顺序被关上。
# Note that an empty string is also considered valid.
# Example:
# Input: "()"
# Output: true
#
# Input: "()[]{}"
# Output: true
#
# Input: "(]"
# Output: false
#
# Input: "([)]"
# Output: false
#
# Input: "{[]}"
# Output: true

解题思路

由于栈拥有先进后出的特性,可以将字符串中每个字符按照一定规则入栈和出栈中,如果放入的是左括号,则入栈,否则出栈并判断。

# Question: 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:
# Input: "()"
# Output: true
#
# Input: "()[]{}"
# Output: true
#
# Input: "(]"
# Output: false
#
# Input: "([)]"
# Output: false
#
# Input: "{[]}"
# Output: true


class Solution:
    def isValid(self, s: str) -> bool:
        bracket_list = {'(': ')', '{': '}', '[': ']'}
        stack = []

        if str == '':
            return True

        for char in s:
            if char in bracket_list.keys():
                stack.append(bracket_list[char])

            else:
                if stack and stack[-1] == char:
                    stack.pop()
                else:
                    return False

        return len(stack) == 0


if __name__ == '__main__':
    s = Solution()
    print(s.isValid('()'))
    print(s.isValid('()[]{}'))
    print(s.isValid('(]'))
    print(s.isValid('([)]'))
    print(s.isValid('{[]}'))
    print(s.isValid(']]]'))

你可能感兴趣的:(Leetcode 20 - Valid Parentheses)