leetcode_day01
任务一:有效的括号
题目链接: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的更多相关文章
随机推荐
- Maven 配置本地依赖jar
现有json-1.0.jar,引入依赖方法如下: 1. 在项目下新建 lib 目录,复制json-1.0.jar到lib目录下 pom.xml中添加配置 <dependency> < ...
- python读取mat文件
一.mat文件 mat数据格式是Matlab的数据存储的标准格式.在Matlab中主要使用load()函数导入一个mat文件,使用save()函数保存一个mat文件.对于文件 load('data.m ...
- Mybatis中的DataSource配置
dataSource 的类型可以配置成其内置类型之一,如 UNPOOLED,POOLED,JNDI. 1.如果将类型设置成 UNPOOLED,MyBatis 会为每一个数据库操作创建一个新的连接,并关 ...
- 第51章 设置FLASH的读写保护及解除—零死角玩转STM32-F429系列
第51章 设置FLASH的读写保护及解除 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.co ...
- noip2018 洛谷 P5020 货币系统
关键: 要使m最小,(m,b)中的数不能用(n,a)中的数表示出来 对于 3 19 10 6 19=10+3+3+3 6=3+3 只有3 和 10 不能被(n,a)中的数表示 所以m=2 只需要 ...
- C#+Winform记事本程序
第17章 记事本 如何使用Visual C# 2010设计一个Windows应用程序——记事本,学习,可以进一步掌握MenuStrip(菜单).ToolStrip(工具栏).RichTextBox(高 ...
- Eclipse+Python环境配置
Eclipse+Pydev 1.安装Eclipse Eclipse可以在它的官方网站Eclipse.org找到并下载,通常我们可以选择适合自己的Eclipse版本,比如Eclipse Classic. ...
- phonegap二维码扫描插件
原文出处:http://rensanning.iteye.com/blog/2034026 谈谈我使用这个的体会吧; git地址 https://github.com/wildabeast/Barco ...
- PHP生成特定长度的纯字母字符串
PHP中,md5().uniqid()函数可以返回32位和13位不重复的字符串,但是这些字符串都可能包含有数字.如果需要纯字母的字符串,而且长度不定,比如8位,那么直接用这两个函数无法达到效果. 这时 ...
- Requests库:python实现的简单易用的http库
1.get请求: get(url, params, headers) 2.json 解析 3.content 获取二进制内容 4.headers 添加 5.post请求:post(url,data,h ...