zoukankan      html  css  js  c++  java
  • Leetcode 20

    题目描述

    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(']]]'))
    
  • 相关阅读:
    HTML标签(二)
    HTML 表单
    HTML列表
    HTML表格
    Critical Section Problems
    Stack, Queue and Priority Queue
    Introduction to Dynamic Set
    Introduction to Divide-and-Conquer
    Sorting Algorithms Overview
    Python学习笔记(三)数据类型
  • 原文地址:https://www.cnblogs.com/michael9/p/11900529.html
Copyright © 2011-2022 走看看