leetCode练题——20. Valid Parentheses
1、题目
20. Valid Parentheses——Easy 
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
 - Open brackets must be closed in the correct order.
 
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}"
Output: true
题目 大致意思是判断给的三种括号组成的字符串是不是对称的。
2、我的解答(copy大神)
大神的做法还是采用了特殊符号字典存储,以后这种几个的符号真的可以直接采用字典存储(罗马符号、括号之类的),简单明了。
1 # -*- coding: utf-8 -*- 2 # @Time : 2020/1/31 10:37 3 # @Author : SmartCat0929 4 # @Email : 1027699719@qq.com 5 # @Link : https://github.com/SmartCat0929 6 # @Site : 7 # @File : 20. Valid Parentheses(copy大神做法).py 8 9 class Solution: 10 def isValid(self, s: str) -> bool: 11 bracket_map = {"(": ")", "[": "]", "{": "}"} 12 open_par = set(["(", "[", "{"]) 13 stack = [] 14 for i in s: 15 if i in open_par: 16 stack.append(i) 17 elif stack and i == bracket_map[stack[-1]]: 18 stack.pop() 19 else: 20 return False 21 return stack == [] 22 print(Solution().isValid("{[[(])]}"))
    既能朝九晚五,又能浪迹天涯!

    
                
            
        
浙公网安备 33010602011771号