专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

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(']]]'))

文章永久链接:https://tech.souyunku.com/21886

未经允许不得转载:搜云库技术团队 » Leetcode 20 - Valid Parentheses

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们