任务一:有效的括号

题目链接: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. 【转】Android Support 包里究竟有什么

    随着 Android 5.0 Lollipop 的发布,Android 又为我们提供了更多的支持包,但是我相信大部分开发者都同我之前一样不知道这些包里究竟有些什么东西,我们应该在什么时候使用它.现在, ...

  2. 近期流行的JavaScript框架与主题

    [新年快乐]2017年你应该关注的JavaScript框架与主题 2017-01-01 王下邀月熊 JavaScript JavaScript的繁荣促生了很多优秀的技术.框架与工具库,这空前的繁荣也给 ...

  3. 卷积神经网络CNN理解

    自今年七月份以来,一直在实验室负责卷积神经网络(Convolutional Neural Network,CNN),期间配置和使用过theano和cuda-convnet.cuda-convnet2. ...

  4. ceph-简介及安装(luminous)版

    什么是ceph: Ceph是一种为优秀的性能.可靠性和可扩展性而设计的统一的.分布式的存储系统.Ceph 独一无二地用统一的系统提供了对象.块.和文件存储功能,它可靠性高.管理简便.并且是开源软件. ...

  5. pooling

    转自:http://www.gageet.com/2014/09182.php 本文部分参考了:http://www.zhihu.com/question/23437871 卷积层是对图像的一个邻域进 ...

  6. BZOJ1202: [HNOI2005]狡猾的商人(带权并查集)

    Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 4577  Solved: 2249[Submit][Status][Discuss] Descript ...

  7. ABAP Table Control

    SAP中,Table Control是在Screen中用的最广泛的控件之一了,可以实现对多行数据的编辑.  简单来说,Table Control是一组屏幕元素在Screen上的重复出现,这就是它与普通 ...

  8. winrar压缩工具

    WinRAR使用心得 免广告 英文版可以设置广告关闭,地址: https://www.win-rar.com/predownload.html?&Version=64bit 把WinRAR默认 ...

  9. dts--framework(一)

    dts 大体框架 framework 定义类 定义方法 tests framework调用所需要的函数 ./dpdk/usertools/cpu_layout.py /sys/devices/syst ...

  10. 谈一谈你对js线程的理解

    js线程:javascript是单线程的,所有任务都需要排队,这些任务分为同步任务和异步任务,单线程上有一个主线程任务.同步任务必须再主线程上排队进行,而异步任务(类似于点击事件)必须在主线程上的任务 ...