任务一:有效的括号

题目链接: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
												

leetcode_day01的更多相关文章

随机推荐

  1. IOC、注入

    转:https://blog.csdn.net/lutianfeiml/article/details/51731219 实际开发中使用XML还是注解 XML: bean管理 注解: 注入属性的时候比 ...

  2. css3中的 @Keyframes

    一.介绍 keyframes被称为关键帧,其类似于Flash中的关键帧.在CSS3中其主要以“@keyframes”开头,后面跟着是动画名称加上一对花括号“{…}”,括号中是一些不同时间段样式规则. ...

  3. 根据值设置select的选中项

    $('.selector').attr("checked", true); <s:iterator value="jobSelect" id=" ...

  4. 史上最简单的SpringCloud教程 | 第三篇: 服务消费者(Feign)

    转载请标明出处: https://www.fangzhipeng.com/springcloud/2017/07/12/sc03-feign/ 本文出自方志朋的博客 最新Finchley版本请访问: ...

  5. 一句话说明==和equals的区别

    public class equals { public static void main(String[] args) { int x=10; int y=10; String str1=new S ...

  6. 第一次发干货Observable.zip与Observable.forkJoin

    在IT界已经混了5年了,5年中浏览了不少的网站,在上面查询自己想要的东西,解决工作中遇到的问题,心里总想有天自己能够有自己的博客,能给分享一些自己在生活中.工作中遇到的问题,让其他有类似经历的朋友能够 ...

  7. Oracle中文乱码解决

    查看当前Oracle字符集 select userenv('language') from dual; USERENV('LANGUAGE') ---------------------------- ...

  8. 【图论 思维】cf715B. Complete The Graph加强

    zzq讲的杂题 题目大意 有一张$n​$个点$m​$条边的简单正权无向图,$S​$到$T​$的最短路为$L​$,现在有一些边的边权未知,请输出任意一种满足题意的方案. $n,m\le 500000​$ ...

  9. Linux中用户与用户组管理

    1.基础知识 Linux作为一种多用户的操作系统(服务器系统),允许多个用户同时登陆到系统上,并响应每个用户的请求. 任何需要使用操作系统的用户,都需要一个系统账号,账号分为:管理员账号与普通用户账号 ...

  10. xml解析之stax

    博文引自:http://zangweiren.iteye.com/blog/647334 Java 6.0对XML支持的新特性有许多方面.比如StAX.针对XML-Web服务的Java架构(JAX-W ...