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的更多相关文章
随机推荐
- LeetCode(Two Sum)
一.题目要求 Given an array of integers, return indices of the two numbers such that they add up to a spec ...
- python与consul 实现gRPC服务注册-发现
背景 通过对gRPC的介绍我们知道,当正常启动服务后,我们只需要知道ip,port就可以进行gRPC的连接.可以想到,这种方式并不适合用于线上环境,因为这样直连的话就失去了扩展性,当需要多机部署的时候 ...
- 利用Kettle转储接口数据
1. 项目背景 1.1. 项目背景 数据接口 API:应用程序接口(Application Program Interface)的简称,是实现计算机软件之间数据通信的工具.同时API也是一种 ...
- 如何把设计图自动转换为iOS代码? 在线等,挺急的!
这是一篇可能略显枯燥的技术深度讨论与实践文章.如何把设计图自动转换为对应的iOS代码?作为一个 iOS开发爱好者,这是我很感兴趣的一个话题.最近也确实有了些许灵感,也确实取得了一点小成果,和大家分享一 ...
- vim指令,快捷键汇总
Vim 命令.操作.快捷键全集 命令历史 以:和/开头的命令都有历史纪录,可以首先键入:或/然后按上下箭头来选择某个历史命令. 启动vim 在命令行窗口中输入以下命令即可 vim 直接启动vim vi ...
- linux 基本命令笔记
nohup [process] & 后台挂起命令nohup 挂起& 后台运行 python3 manage.py runserver 0.0.0.0:8080 python -r 递 ...
- 判断StringBuilder 是否为空
if("".equals(stringbuilder.toString())) do..
- maven 使用错误
使用mvn test mvn test -Dtest=测试包名.测试类名时 [ERROR] Failed to execute goal org.apache.maven.plugins:maven- ...
- python系列3之内置函数和文件操作
目录 自定义函数 内置函数 文件的操作 练习题 一. 自定义函数 1. 函数的创建 函数的创建 1.def关键字 2.函数名+() 3.冒号 4.缩进 5. return返回值,可以不写,默认的返回值 ...
- linux最大进程数
使用 ulimit -a 命令,查看 max user processes 的输出,就是系统最大进程数 core file size (blocks, -c) unlimited data seg s ...