任务一:有效的括号

题目链接:https://leetcode-cn.com/problems/valid-parentheses/

自己的答案:

 class Solution:
def isValid(self, s):
s = list(s)
length = len(s) #空字符串被认为是有效字符串
if length == 0:
return True stringList = ['(', ')', '[', ']', '{', '}']
for s_element in s:
if s_element not in stringList:
return False counter1 = 0
counter2 = 0
counter3 = 0
for s_ele in s:
if s_ele == "(":
counter1 += 1
elif s_ele == ")":
counter1 -= 1
elif s_ele == "[":
counter2 += 1
elif s_ele == "]":
counter2 -= 1
elif s_ele == "{":
counter3 += 1
elif s_ele == "}":
counter3 -= 1
if counter1 == 0 and counter2 == 0 and counter3 == 0:
return True
else:
return False

官方答案:

 class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
""" # The stack to keep track of opening brackets.
stack = [] # Hash map for keeping track of mappings. This keeps the code very clean.
# Also makes adding more types of parenthesis easier
mapping = {")": "(", "}": "{", "]": "["} # For every bracket in the expression.
for char in s: # If the character is an closing bracket
if char in mapping: # Pop the topmost element from the stack, if it is non empty
# Otherwise assign a dummy value of '#' to the top_element variable
top_element = stack.pop() if stack else '#' # The mapping for the opening bracket in our hash and the top
# element of the stack don't match, return False
if mapping[char] != top_element:
return False
else:
# We have an opening bracket, simply push it onto the stack.
stack.append(char) # In the end, if the stack is empty, then we have a valid expression.
# The stack won't be empty for cases like ((()
return not stack
												

最新文章

  1. UIImagePickerControllerDelegate---ActionSheet---获得设备型号
  2. python开启简单webserver
  3. HoverTree菜单0.1.3新增效果
  4. C++输入输出
  5. centos时间同步方法
  6. sdutoj 2154 Shopping
  7. Brush Mode --- Nyoj 236 分类: Brush Mode 2014-04-02 06:56 116人阅读 评论(0) 收藏
  8. 在PyQt4中使用matplotlib
  9. Android开发之漫漫长途 XII——Fragment详解
  10. django drf 开发 ~ models基础学习
  11. spring cloud_1_mm_eureka2 eureka集群
  12. 用函数式编程对JavaScript进行断舍离
  13. 002.MongoDB社区版安装
  14. docker 2 容器数据卷
  15. 启动studio报错Gradle error
  16. FreeMarker快速入门
  17. SpringBoot集成Jersey
  18. C#找出接口的所有实现类并遍历执行这些类的公共方法
  19. ES6的新增数据类型:Symbol
  20. centos7 禁用每次sudo 需要输入密码

热门文章

  1. 2018.9.9 Tomcat是怎样运行的
  2. Java 字符串转码工具类
  3. Spring MVC的一些学习笔记-入门配置和HttpMessageConverter
  4. Mac下安装OpenCV3.0和Anaconda和环境变量设置
  5. C#操作Word,写数据,插入图片
  6. td过长,将固定宽度table撑开
  7. 如何使用MongoDB+Springboot实现分布式ID?
  8. java基础 序列化反序列化流 实现Serializable 接口 自动装载序列号到对象文本文件如修改不能反序列化对象文本,除非自定义long型常量 打印流
  9. AsyncDisplayKit技术分析
  10. MySQL 5.7传统复制到GTID在线切换(一主一从)