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大神)
大神的做法还是采用了特殊符号字典存储,以后这种几个的符号真的可以直接采用字典存储(罗马符号、括号之类的),简单明了。
# -*- coding: utf-8 -*-
# @Time : 2020/1/31 10:37
# @Author : SmartCat0929
# @Email : 1027699719@qq.com
# @Link : https://github.com/SmartCat0929
# @Site :
# @File : 20. Valid Parentheses(copy大神做法).py class Solution:
def isValid(self, s: str) -> bool:
bracket_map = {"(": ")", "[": "]", "{": "}"}
open_par = set(["(", "[", "{"])
stack = []
for i in s:
if i in open_par:
stack.append(i)
elif stack and i == bracket_map[stack[-1]]:
stack.pop()
else:
return False
return stack == []
print(Solution().isValid("{[[(])]}"))