• 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(']]]'))
    
  • 相关阅读:
    利用JNI技术在Android中调用、调试C++代码
    iOS在线更新framework,使用NSBundle动态读取
    CocoaPods pod install
    Quartz 2D在ios中的使用简述二:创建画布
    iOS并发编程笔记【转】
    openCV C++ 代码笔记
    Quartz 2D在ios中的使用简述一:坐标体系
    ios视频播放器,代码和界面分离
    mac显示和隐藏文件
    3点画圆
  • 原文地址:https://www.cnblogs.com/michael9/p/11900529.html
Copyright © 2020-2023  润新知